<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sidharth J Dev on Medium]]></title>
        <description><![CDATA[Stories by Sidharth J Dev on Medium]]></description>
        <link>https://medium.com/@sidjdev?source=rss-75ba9d0e7c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*370m2VCeEz8lzjnZ.jpg</url>
            <title>Stories by Sidharth J Dev on Medium</title>
            <link>https://medium.com/@sidjdev?source=rss-75ba9d0e7c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:44:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sidjdev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Munich (2005): A Dissection of Terrorism.]]></title>
            <link>https://medium.com/@sidjdev/munich-2005-a-dissection-of-terrorism-f617fd799b5e?source=rss-75ba9d0e7c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f617fd799b5e</guid>
            <category><![CDATA[movıe]]></category>
            <category><![CDATA[steven-spielberg]]></category>
            <dc:creator><![CDATA[Sidharth J Dev]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 12:08:28 GMT</pubDate>
            <atom:updated>2023-08-28T12:08:28.055Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9RQIpYI1DmTDvNud9CS2Q.jpeg" /></figure><p>Very rarely might one write a review about a movie and make it mostly, if not all, about the director, but <strong>Munich</strong> is such a film.</p><p>Munich tells the story of a secret ploy executed by Mossad in retaliation against the murder of Israeli athletes and their coach at the hands of Palestinian militants. The conflict between Israel and Palestine is one of the oldest in history. The Munich massacre and the subsequent retaliation are among the bloodiest chapters in that history. The subject is bound to inflame a lot of political sensitivities as well as personal feelings all around the world. Therein lies the first and major achievement of the film.</p><p>Munich never pulls its punches when it addresses the brutality of blood and death. Yet, it does not glorify the Mossad operatives. It does not glamorize violence, nor does it justify it. It simply shows it on the big screen. In its truest sense, it lets the audience decide for themselves where their sympathies should lie. Spielberg is not a man devoid of political sympathies, nor is he insensitive to tragedy. He proved that with Schindler’s List. But he elegantly managed to rise above his personal sentiments (wherever they might lie) when it came to filming this piece of art. The reason such an approach was the right way to tackle this story is that this is the kind of story or event that people need to know about and understand to its core, to appreciate that right and wrong are not so simple in the world.</p><p>Steven Spielberg is a director who is most known for his craft of cinema. Now, what does it mean to have craft over cinema? In the simplest terms, it is the ability to understand how every aspect of a movie works together seamlessly to convey the story and emotion to the audience perfectly. Whether it be the fun adrenaline rush we get from watching Raiders of The Lost Ark, being absolutely terrified of the sea after watching Jaws, or being heartbroken by the death of (a rather ugly) alien in The Extra Terrestrial, Spielberg has got everything covered. He used a storytelling technique in Munich that is rather similar to what he did in Schindler’s List. A slow burner approach where we are taken into the story without a true hint of the horrors that await us. The opening sequence of the Palestinian attack was rather veiled in approach. We are introduced to the story through the protagonist Avner Kaufman, played by the remarkable Eric Bana. When Avner is confronted with the task of assembling a task force to commit these murders, Spielberg manages to put the audience in a similar situation as Avner. We have a detached sense of the possibility of a person committing murder. It is here that the hooks of the movie sink into the audience, without us even realizing it. With a likable and relatable (as a person with a family) lead, we can’t help but root for his success and put ourselves in Avner’s shoes.</p><p>When we are comfortably settled in those shoes, Spielberg starts leading Avner, and in effect us, through darker roads. Here, the great craftsman makes us feel the horror of taking a life, the horrors of collateral damage, and the horrors of blood in the wind. Earlier in the movie, a character jokes about the paranoia of a retired agent, the paranoia of someone who fears that they might be murdered at any point. What can be easily dismissed as a silly anecdote comes back with force when we see Avner becoming just as paranoid towards the end. What is more amazing is that this paranoia doesn’t feel out of place. It will be felt by everyone watching it. Deftly, he sets up the most amazing use of Chekov’s gun.</p><p>The word “terrorism” is defined as an act of violence or intimidation for political aims. It is unfortunate that it is understood in a much narrower way today. Munich manages to portray terrorists as clean-cut, Caucasian gentlemen wearing suits. It is here that the film’s political achievement needs the most commendation. And if you, as the audience, are tempted to sympathize with their cause, it is then that you need to reassess your perspectives on many conflicts that you might view in black and white.</p><p>It might be sacrilegious to place one work of such a great artist above the rest of his commercially and critically acclaimed works, but I believe that Munich is the most technically perfect movie that Steven Spielberg has made.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f617fd799b5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Network Layer in Combine]]></title>
            <link>https://medium.com/@sidjdev/simple-network-layer-in-combine-63b634269796?source=rss-75ba9d0e7c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/63b634269796</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-programming]]></category>
            <category><![CDATA[combine]]></category>
            <dc:creator><![CDATA[Sidharth J Dev]]></dc:creator>
            <pubDate>Wed, 10 May 2023 11:19:36 GMT</pubDate>
            <atom:updated>2023-05-10T11:19:36.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GJwUF47y6LUouFPo" /><figcaption>Photo by <a href="https://unsplash.com/@agforl24?utm_source=medium&amp;utm_medium=referral">Tai Bui</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” — Martin Fowler</blockquote><p>In my iOS projects, I’ve come to realize that crafting a functional and efficient Network Layer is an ongoing adventure. It’s like a constantly evolving puzzle that keeps me on my toes. With each new project, I strive to make improvements to the Network Layer, always aiming for a smoother experience than before. However, I’ve also learned that sometimes, in the pursuit of perfection, I can get caught up in overthinking and unnecessary complexity.</p><p>Recently, I took a step back and approached things differently. I decided to focus on creating a clean and straightforward class to handle network calls in my iOS app. By simplifying and streamlining the process, I hope to achieve a more sensible and enjoyable development experience. Join me on this journey as we unravel the mysteries of the Network Layer and discover the beauty of simplicity in handling our network requests.</p><h3><strong>Let’s Start Then!</strong></h3><p>Before we get to the Network Layer, I think we can create a simple <strong>ResponseWrapper. </strong>Usually, an API response will have the following structure</p><pre>{<br>  &quot;message&quot;: &quot;success&quot;,<br>  &quot;status&quot;: 200,<br>  &quot;data&quot;: {<br>    &quot;id&quot;: 123,<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;email&quot;: &quot;johndoe@example.com&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;city&quot;: &quot;New York&quot;<br>  }<br>}</pre><p>Bearing this format in mind, let’s proceed to make a Class to handle the response.</p><pre>struct ResponseWrapper&lt;T: Decodable&gt;: Decodable {<br>    let status: Int?<br>    let message: String?<br>    let data: T?<br>    <br>    init(from decoder: Decoder) throws {<br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        status = try container.decodeIfPresent(Int.self, forKey: .status)<br>        message = try container.decodeIfPresent(String.self, forKey: .message)<br>        data = try container.decodeIfPresent(T.self, forKey: .data)<br>    }<br>    <br>    private enum CodingKeys: String, CodingKey {<br>        case status<br>        case message<br>        case data<br>    }<br>}</pre><p>Having the status, message, and data as optional parameters provides me with peace of mind when deploying the code to production. I prefer handling guarded unwrapping over encountering a fatalError .</p><p>Enabling the decoder through CodingKeys enhances the flexibility and reusability of the <strong>Wrapper</strong>, allowing it to adapt to new developer and backend naming conventions.</p><h3>The Network Layer</h3><ul><li><strong>Error Handling</strong></li></ul><p>I decided to stick to an enum based approach, here. So let’s start with some simple error handling-</p><pre>enum APIError: Error {<br>    case invalidURL<br>    case requestFailed(String)<br>    case decodingFailed<br>}<br><br>enum HttpMethod: String {<br>    case get = &quot;GET&quot;<br>    case post = &quot;POST&quot;<br>    case put = &quot;PUT&quot;<br>    case delete = &quot;DELETE&quot;<br>}</pre><p>This part is fairly self-explanatory, I am sure. With APIError we can handle the obvious and expected error responses that we get from the API. Same simplicity was used to create a set of enums for handling HTTPMethods.</p><ul><li><strong>Endpoints</strong></li></ul><p>Now we shall proceed to create the endpoints required in our app. This too, shall follow the enum pattern we have created for the Error extension-</p><pre>enum Endpoint {<br>    case examplePostOne<br>    case examplePutOne<br>    case exampleDelete<br>    case examplePostTwo<br>    case exampleGet<br>    case examplePutTwo<br>    <br>    var path: String {<br>        switch self {<br>        case .examplePostOne:<br>            return &quot;/api/postOne&quot;<br>        case .examplePutOne:<br>            return &quot;/api/putOne&quot;<br>        case .exampleDelete:<br>            return &quot;/api/delete&quot;<br>        case .examplePostTwo:<br>            return &quot;/api/postTwo&quot;<br>        case .exampleGet:<br>            return &quot;/api/get&quot;<br>        case .examplePutTwo:<br>            return &quot;/api/puTwo&quot;<br>        }<br>    }<br>    <br>    var httpMethod: HttpMethod {<br>        switch self {<br>        case .exampleGet:<br>            return .get<br>        case .examplePostOne, .examplePostTwo:<br>            return .post<br>        case .examplePutOne, .examplePutTwo:<br>            return .put<br>        case .exampleDelete:<br>            return .delete<br>        }<br>    }<br>}</pre><p>This approach enables us to access the URLEndpoints and HTTPMethods easily, using the following methods-</p><pre>let endPoint: Endpoint = Endpoint.examplePostOne<br>print(endPoint.path) // prints &quot;/api/postOne&quot;<br>print(endPoint.httpMethod) // .post</pre><p>As the complexity of the app increases and more API endpoints are to be added, we can do it here inside the enum Endpoint , and add the HTTPMethod, with it. This will be a single Source Of Truth for our API endpoints.</p><ul><li><strong>Network Request</strong></li></ul><p>Next we make a very basic NetworkManager class to hold our request function. We shall use the Combine Framework to implement this functionality-</p><pre>protocol NetworkService {<br>    func request&lt;T: Decodable&gt;(_ endpoint: Endpoint, parameters: Encodable?) -&gt; AnyPublisher&lt;T, APIError&gt;<br>}<br><br>class NetworkManager: NetworkService {<br>    private let baseURL: String<br>    <br>    init(baseURL: String = &quot;&quot;) {<br>        self.baseURL = environment.baseURL<br>    }<br>    <br>    func request&lt;T: Decodable&gt;(_ endpoint: Endpoint, parameters: Encodable? = nil) -&gt; AnyPublisher&lt;T, APIError&gt; {<br>            guard let url = URL(string: baseURL + endpoint.path) else {<br>                return Fail(error: APIError.invalidURL).eraseToAnyPublisher()<br>            }<br>            var urlRequest = URLRequest(url: url)<br>            <br>            if let parameters = parameters {<br>                urlRequest.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>                do {<br>                    let jsonData = try JSONEncoder().encode(parameters)<br>                    urlRequest.httpBody = jsonData<br>                } catch {<br>                    return Fail(error: APIError.requestFailed(&quot;Encoding parameters failed.&quot;)).eraseToAnyPublisher()<br>                }<br>            }<br>            return URLSession.shared.dataTaskPublisher(for: urlRequest)<br>                .tryMap { (data, response) -&gt; Data in<br>                    if let httpResponse = response as? HTTPURLResponse,<br>                       (200..&lt;300).contains(httpResponse.statusCode) {<br>                        return data<br>                    } else {<br>                        let statusCode = (response as? HTTPURLResponse)?.statusCode ?? -1<br>                        throw APIError.requestFailed(&quot;Request failed with status code: \(statusCode)&quot;)<br>                    }<br>                }<br>                .decode(type: ResponseWrapper&lt;T&gt;.self, decoder: JSONDecoder())<br>                .tryMap { (responseWrapper) -&gt; T in<br>                    guard let status = responseWrapper.status else {<br>                        throw APIError.requestFailed(&quot;Missing status.&quot;)<br>                    }<br>                    switch status {<br>                    case 200:<br>                        guard let data = responseWrapper.data else {<br>                            throw APIError.requestFailed(&quot;Missing data.&quot;)<br>                        }<br>                        return data<br>                    default:<br>                        let message = responseWrapper.message ?? &quot;An error occurred.&quot;<br>                        throw APIError.requestFailed(message)<br>                    }<br>                }<br>                .mapError { error -&gt; APIError in<br>                    if error is DecodingError {<br>                        return APIError.decodingFailed<br>                    } else if let apiError = error as? APIError {<br>                        return apiError<br>                    } else {<br>                        return APIError.requestFailed(&quot;An unknown error occurred.&quot;)<br>                    }<br>                }<br>                .eraseToAnyPublisher()<br>        }<br>}<br></pre><p>Let us set the baseURL as an empty string to start off, here. We can modify that later. One thing to notice here is the generic T we are using to refer to the decodable. What we are trying to do here, is to let the function know the data type to which we would like to decode our response to. We have created the ResponseWrapper earlier but that is not where should map the final result to. We need to decode the value that we expect to receive inside data key.</p><p>So, we use .decode on ResponseWrapper which tries to match its data to the very data type that we pass in (don’t worry, this will be clearer, once we try to fetch data). Once the decoding is done successfully on ResponseWrapper we look for status, message and data inside it. If the decoding fails, we try to connect the reason of failure, to appropriate APIError .</p><ul><li><strong>BaseURL</strong></li></ul><p>We could’ve passed in a simple string for baseURL, but it is a common and neat practise to have a development, staging and production environment, while working as part of a team and when working for an outside client. So to have a clean release cycle, we can classify the baseURL as so-</p><pre>enum APIEnvironment {<br>    case development<br>    case staging<br>    case production<br>    <br>    var baseURL: String {<br>        switch self {<br>        case .development:<br>            return &quot;development.example.com&quot;<br>        case .staging:<br>            return &quot;staging.example.com&quot;<br>        case .production:<br>            return &quot;production.example.com&quot;<br>        }<br>    }<br>}</pre><p>Let us now modify the initialisation for NetworkManager -</p><pre>init(environment: APIEnvironment = NetworkManager.defaultEnvironment()) {<br>        self.baseURL = environment.baseURL<br>    }<br>    <br>    static func defaultEnvironment() -&gt; APIEnvironment {<br>#if DEBUG<br>        return .development<br>#elseif STAGING<br>        return .staging<br>#else<br>        return .production<br>#endif<br>    }</pre><p>#if DEBUG is provided by the compiler. You can define your own custom flags or build configurations, such as STAGING, to differentiate between different environments during the build process. This is a cleaner way to initialise the class from a ViewModel where we might try to access the NetworkManager from.</p><ul><li><strong>Headers</strong></li></ul><p>We can add custom header elements as well, as they tend to come in handy.</p><pre>private func defaultHeaders() -&gt; [String: String] {<br>        var headers: [String: String] = [<br>            &quot;Platform&quot;: &quot;iOS&quot;,<br>            &quot;User-Token&quot;: &quot;your_user_token&quot;,<br>            &quot;uid&quot;: &quot;user-id&quot;<br>        ]<br>        <br>        if let appVersion = Bundle.main.infoDictionary?[&quot;CFBundleShortVersionString&quot;] as? String {<br>            headers[&quot;App-Version&quot;] = appVersion<br>        }<br>        <br>        return headers<br>    }</pre><p>We can add elements like auth-token, refresh-token etc in our headers. Of course, now that we have created the headers, we need to include them in the API call, as well.</p><p>First, let’s change the function call-</p><pre>protocol NetworkService {<br>    func request&lt;T: Decodable&gt;(_ endpoint: Endpoint, headers: [String: String]?, parameters: Encodable?) -&gt; AnyPublisher&lt;T, APIError&gt;<br>}</pre><p>And then, we add the httpMethod inclusion in the function definition-</p><pre>func request&lt;T: Decodable&gt;(_ endpoint: Endpoint, headers: [String: String]? = nil, parameters: Encodable? = nil) -&gt; AnyPublisher&lt;T, APIError&gt; {<br>            guard let url = URL(string: baseURL + endpoint.path) else {<br>                return Fail(error: APIError.invalidURL).eraseToAnyPublisher()<br>            }<br>            var urlRequest = URLRequest(url: url)<br>            urlRequest.httpMethod = endpoint.httpMethod.rawValue<br>            let allHeaders = defaultHeaders().merging(headers ?? [:], uniquingKeysWith: { (_, new) in new })<br>                for (key, value) in allHeaders {<br>                    urlRequest.setValue(value, forHTTPHeaderField: key)<br>            }<br>.<br>.<br>.<br>.<br>.<br>.<br>}</pre><p>With this, we have the function definition, sorted out. When we combine everything, we get this-</p><pre>import Foundation<br>import Combine<br><br>enum APIError: Error {<br>    case invalidURL<br>    case requestFailed(String)<br>    case decodingFailed<br>}<br><br>enum HttpMethod: String {<br>    case get = &quot;GET&quot;<br>    case post = &quot;POST&quot;<br>    case put = &quot;PUT&quot;<br>    case delete = &quot;DELETE&quot;<br>}<br><br>enum Endpoint {<br>    case examplePostOne<br>    case examplePutOne<br>    case exampleDelete<br>    case examplePostTwo<br>    case exampleGet<br>    case examplePutTwo<br>    <br>    var path: String {<br>        switch self {<br>        case .examplePostOne:<br>            return &quot;/api/postOne&quot;<br>        case .examplePutOne:<br>            return &quot;/api/putOne&quot;<br>        case .exampleDelete:<br>            return &quot;/api/delete&quot;<br>        case .examplePostTwo:<br>            return &quot;/api/postTwo&quot;<br>        case .exampleGet:<br>            return &quot;/api/get&quot;<br>        case .examplePutTwo:<br>            return &quot;/api/puTwo&quot;<br>        }<br>    }<br>    <br>    var httpMethod: HttpMethod {<br>        switch self {<br>        case .exampleGet:<br>            return .get<br>        case .examplePostOne, .examplePostTwo:<br>            return .post<br>        case .examplePutOne, .examplePutTwo:<br>            return .put<br>        case .exampleDelete:<br>            return .delete<br>        }<br>    }<br>}<br><br>enum APIEnvironment {<br>    case development<br>    case staging<br>    case production<br>    <br>    var baseURL: String {<br>        switch self {<br>        case .development:<br>            return &quot;development.example.com&quot;<br>        case .staging:<br>            return &quot;staging.example.com&quot;<br>        case .production:<br>            return &quot;production.example.com&quot;<br>        }<br>    }<br>}<br><br>protocol NetworkService {<br>    func request&lt;T: Decodable&gt;(_ endpoint: Endpoint, headers: [String: String]?, parameters: Encodable?) -&gt; AnyPublisher&lt;T, APIError&gt;<br>}<br><br><br><br>class NetworkManager: NetworkService {<br>    private let baseURL: String<br>    <br>    init(environment: APIEnvironment = NetworkManager.defaultEnvironment()) {<br>        self.baseURL = environment.baseURL<br>    }<br>    <br>    static func defaultEnvironment() -&gt; APIEnvironment {<br>#if DEBUG<br>        return .development<br>#elseif STAGING<br>        return .staging<br>#else<br>        return .production<br>#endif<br>    }<br>    <br>    private func defaultHeaders() -&gt; [String: String] {<br>        var headers: [String: String] = [<br>            &quot;Platform&quot;: &quot;iOS&quot;,<br>            &quot;User-Token&quot;: &quot;your_user_token&quot;,<br>            &quot;uid&quot;: &quot;user-id&quot;<br>        ]<br>        <br>        if let appVersion = Bundle.main.infoDictionary?[&quot;CFBundleShortVersionString&quot;] as? String {<br>            headers[&quot;App-Version&quot;] = appVersion<br>        }<br>        <br>        return headers<br>    }<br>    <br>    func request&lt;T: Decodable&gt;(_ endpoint: Endpoint, headers: [String: String]? = nil, parameters: Encodable? = nil) -&gt; AnyPublisher&lt;T, APIError&gt; {<br>            guard let url = URL(string: baseURL + endpoint.path) else {<br>                return Fail(error: APIError.invalidURL).eraseToAnyPublisher()<br>            }<br>            var urlRequest = URLRequest(url: url)<br>            urlRequest.httpMethod = endpoint.httpMethod.rawValue<br>            let allHeaders = defaultHeaders().merging(headers ?? [:], uniquingKeysWith: { (_, new) in new })<br>                for (key, value) in allHeaders {<br>                    urlRequest.setValue(value, forHTTPHeaderField: key)<br>            }<br>            if let parameters = parameters {<br>                urlRequest.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>                do {<br>                    let jsonData = try JSONEncoder().encode(parameters)<br>                    urlRequest.httpBody = jsonData<br>                } catch {<br>                    return Fail(error: APIError.requestFailed(&quot;Encoding parameters failed.&quot;)).eraseToAnyPublisher()<br>                }<br>            }<br>            return URLSession.shared.dataTaskPublisher(for: urlRequest)<br>                .tryMap { (data, response) -&gt; Data in<br>                    if let httpResponse = response as? HTTPURLResponse,<br>                       (200..&lt;300).contains(httpResponse.statusCode) {<br>                        return data<br>                    } else {<br>                        let statusCode = (response as? HTTPURLResponse)?.statusCode ?? -1<br>                        throw APIError.requestFailed(&quot;Request failed with status code: \(statusCode)&quot;)<br>                    }<br>                }<br>                .decode(type: ResponseWrapper&lt;T&gt;.self, decoder: JSONDecoder())<br>                .tryMap { (responseWrapper) -&gt; T in<br>                    guard let status = responseWrapper.status else {<br>                        throw APIError.requestFailed(&quot;Missing status.&quot;)<br>                    }<br>                    switch status {<br>                    case 200:<br>                        guard let data = responseWrapper.data else {<br>                            throw APIError.requestFailed(&quot;Missing data.&quot;)<br>                        }<br>                        return data<br>                    default:<br>                        let message = responseWrapper.message ?? &quot;An error occurred.&quot;<br>                        throw APIError.requestFailed(message)<br>                    }<br>                }<br>                .mapError { error -&gt; APIError in<br>                    if error is DecodingError {<br>                        return APIError.decodingFailed<br>                    } else if let apiError = error as? APIError {<br>                        return apiError<br>                    } else {<br>                        return APIError.requestFailed(&quot;An unknown error occurred.&quot;)<br>                    }<br>                }<br>                .eraseToAnyPublisher()<br>        }<br>}</pre><ul><li><strong>Fetch Request</strong></li></ul><p>Let us assume that we are expecting a response for the API .exampleGet in the following format-</p><pre>{<br>  &quot;message&quot;: &quot;success&quot;,<br>  &quot;status&quot;: 200,<br>  &quot;data&quot;: {<br>    &quot;id&quot;: 123,<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;email&quot;: &quot;johndoe@example.com&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;city&quot;: &quot;New York&quot;<br>  }<br>}</pre><p>We will start off by creating a new struct- ResponseModel that conforms to Codable protocol.</p><pre>struct ResponseModel: Codable {<br>  var id: Int<br>  var name: String<br>  var email: String<br>  var age: Int<br>  var city: String<br>}</pre><p>As you may notice, we don’t have to worry about message and status keys since that is taken care of, by the ResponseWrapper . We are just providing for the data key in ResponseWrapper .</p><p>Next, we can create a ViewModel and call the request function-</p><pre>import Foundation<br>import Combine<br><br>class ResponseViewModel: ObservableObject {<br>    <br>    private let networkService: NetworkService<br>    private var cancellables: Set&lt;AnyCancellable&gt; = []<br>    <br>    init(networkService: NetworkService = NetworkManager()) {<br>        self.networkService = networkService<br>    }<br>    <br>    func signUp(onCompletion: @escaping (Bool) -&gt; ())  {<br>        let response: AnyPublisher&lt;ResponseModel, APIError&gt; = networkService.request(.exampleGet, headers: nil)<br>        response<br>            .sink { completion in<br>                switch completion {<br>                    case .finished:<br>                        break<br>                    case .failure(let error):<br>                        print(&quot;Error: \(error)&quot;)<br>                        onCompletion(false)<br>                }<br>            }<br>            receiveValue: { response in<br>                print(response)<br>                <br>                onCompletion(true)<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><p>When we pass in ResponseModel for the request function, we are effectively doing a double decoding. First we the function maps the response to ResponseWrapper , and once that is done, it tries to unwrap the data by matching it to ResponseModel . This sets up a clean structure for API response and API Parsing, which would be integral for setting up clean code.</p><p>And there you have it. A reusable Network Layer that is flexible and scalable.</p><p>Feel free to make it better and make it yours.</p><p>Cheers. Happy Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63b634269796" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Navigation Drawer with SwiftUI]]></title>
            <link>https://levelup.gitconnected.com/creating-navigation-drawer-with-swiftui-891663dd32d2?source=rss-75ba9d0e7c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/891663dd32d2</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[navigation-drawer]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[xcode11]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Sidharth J Dev]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 13:31:00 GMT</pubDate>
            <atom:updated>2022-04-25T11:12:04.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ONqrDbxnZdv6y5v2X8AAw.jpeg" /><figcaption>It’s all about order!</figcaption></figure><p>Most iOS developers out there would absolutely dread it when the design demands of a Navigation Drawer in their iOS app. Simply put, there is no direct way to implement it from iOS. I am not a fan of this design, because it is so un-iOS like. Having said that, when the need arises, we must put aside our differences and get the job done.</p><p>Until now, I have been dependent on libraries like SWRevealViewController for this. I tried subclassing Segues to make this work without being dependant on CocoaPods too much, but it was too hard. That changed recently, with me starting to learn SwiftUI.</p><p>So here is my code, implementing a Custom Navigation Drawer, using SwiftUI -</p><p>Let’s start with creating a Model for Menu Items</p><pre>class MenuContent: Identifiable, ObservableObject {</pre><pre><strong>    </strong>var id = UUID()<br><strong>    </strong>var name: String = &quot;&quot;<br>    var image: String = &quot;&quot;</pre><pre><strong>    </strong>init(name: String, image: String) {<br><strong>        </strong>self.name = name<br>        self.image = image<br>    }</pre><pre>}</pre><p>This is a pretty straightforward definition of a Model. We give the menu a Title(name)and an Icon(image).</p><blockquote>We conform our Class MenuContent to Identifiable and ObservableObject so that the list created from this class remains distinct(unique elements with Identifier represented by UUID) and we can observe changes made on the class object, respectively.</blockquote><p>Next we can create a list of menuContents as a testData.</p><pre>let menuHome = MenuContent(name: &quot;Home&quot;, image: <strong>&quot;house.fill&quot;</strong>)</pre><pre>let menuProfile = MenuContent(name: &quot;Profile&quot;, image: <strong>&quot;person.fill&quot;</strong>)</pre><pre>let menuChat = MenuContent(name: &quot;Chat&quot;, image: <strong>&quot;message.fill&quot;</strong>)</pre><pre>let menuLogout = MenuContent(name: &quot;Logout&quot;, image: <strong>&quot;power&quot;</strong>)</pre><pre>let menuContents = [menuHome, menuProfile, menuChat, menuLogout]</pre><p>In WWDC 2019, Apple introduced <strong>SF Symbols</strong> and it has been gorgeous. A library of <em>Vector</em> images that we can use in our apps. Since they are <em>Vector</em> images, they are scalable and easily customisable. The image variable is accepting String names that match the title of Images available in <strong>SF Symbols.</strong></p><p>For more information on<strong> SF Symbols</strong>, check out the official documentation below-</p><p><a href="https://developer.apple.com/design/human-interface-guidelines/sf-symbols/overview/">SF Symbols - SF Symbols - Human Interface Guidelines - Apple Developer</a></p><p>Now, let’s design our Home Screen-</p><pre>struct ContentView: View {<br>    var menu: [MenuContent] = menuContents<br>    var body: some View {<br>        <strong>List(menu)</strong> { menuItem in<strong><br>            MenuCell(menuItem: menuItem)</strong>.onTapGesture {}<br>        }<br>    }<br>}</pre><pre>struct <strong>MenuCell</strong>: View {</pre><pre><strong>    </strong>var menuItem: MenuContent = menuContents[0]<br>    var body: some View {<br>        <strong>HStack</strong> {<br>            <strong>Image</strong>(systemName: menuItem.image)<br>                .foregroundColor(<br>                    .orange)<br>            <strong>Text</strong>(menuItem.name)<br>                .foregroundColor(<br>                    .orange)<br>        }<br>    }<br> }</pre><p>HomeScreen (ContentView) is now rendering a single List on the array menu . We have also created a separate View to render MenuCell(old habits from UITableView).</p><p>This code will give us the following output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*s8GQ2PczHL9Wmafqgg9wjw.gif" /><figcaption>Menu</figcaption></figure><p>Now let’s add a Target View for the menu item-</p><pre>struct <strong>HomeView</strong>: View {<br>    var body: some View {<br>        <strong>ZStack</strong> {<br>            Color.black.edgesIgnoringSafeArea(<br>                .all)<br>            <strong>VStack</strong>(alignment: .leading) {<br>                <strong>Button</strong>(action: {}) {<br>                    Image(systemName: &quot;line.horizontal.3&quot;)<br>                        .foregroundColor(.white)<br>                }<br>                .frame(width: 50.0, height: 50.0)<br>                <strong>Spacer()</strong><br>                <strong>Text</strong>(&quot;This Is Home&quot;)<br>                    .font(<br>                        .largeTitle)<br>                    .foregroundColor(<br>                        .white)<br>                    .frame(maxWidth: .infinity)<br>                <strong>Spacer()</strong><br>            }.padding(.horizontal) .frame(maxWidth: .infinity)<br>        }<br>    }<br>}</pre><p>We can add this View to our ContentView on top of its existing Menu List as the next element on an ZStack</p><pre>struct ContentView: View {<br>    var menu: [MenuContent] = menuContents<br>    var body: some View {<br>        ZStack {<br>            <strong>List(menu)</strong> { menuItem in<br>                MenuCell(menuItem: menuItem).onTapGesture {<br>                    self.menuItemSelected = menuItem<br>                }<br>            }<br>            <strong>HomeView()</strong><br>        }<br>    }<br>}</pre><p>After adding HomeView() we won’t be able to see our existing Menu List, because the HomeView draws itself on top of the Menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*TAc9Qry0z66N74_iHSmOWg.png" /></figure><p>What might happen if we add an offset property to our HomeView ?</p><pre>struct HomeView: View {<br>    var body: some View {<br>        ZStack {<br>            Color.black.edgesIgnoringSafeArea(<br>                .all)<br>            VStack(alignment: .leading) {<br>                Button(action: {}) {<br>                    Image(systemName: &quot;line.horizontal.3&quot;)<br>                        .foregroundColor(.white)<br>                }<br>                .frame(width: 50.0, height: 50.0)<br>                Spacer()<br>                Text(&quot;This Is Home&quot;)<br>                    .font(<br>                        .largeTitle)<br>                    .foregroundColor(<br>                        .white)<br>                    .frame(maxWidth: .infinity)<br>                Spacer()<br>            }.padding(.horizontal) .frame(maxWidth: .infinity)<br>        }<br>        <strong>.offset(x: 200.0, y: 0)</strong><br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*i54dkGlbFTGwLIRr1CwRuA.png" /><figcaption>HomeView being rendered from ContentView</figcaption></figure><p>Isn’t this interesting? Now, the View rendered on the ZStack is pushed away. This gives it the appearance of a Navigation Drawer. Let’s now add an @State var property inside the HomeView on which we can dynamically switch the MenuShowing Property-</p><pre>struct HomeView: View {<br>    <a href="http://twitter.com/State"><strong>@State</strong></a><strong> private var showingMenu = false</strong><br>    var body: some View {<br>        ZStack {<br>            Color.black.edgesIgnoringSafeArea(<br>                .all)<br>            VStack(alignment: .leading) {<br>                Button(action: {<strong>self.showingMenu.toggle()</strong>}) {<br>                    Image(systemName: &quot;line.horizontal.3&quot;)<br>                        .foregroundColor(.white)<br>                }<br>                .frame(width: 50.0, height: 50.0)<br>                Spacer()<br>                Text(&quot;This Is Home&quot;)<br>                    .font(<br>                        .largeTitle)<br>                    .foregroundColor(<br>                        .white)<br>                    .frame(maxWidth: .infinity)<br>                Spacer()<br>            }.padding(.horizontal) .frame(maxWidth: .infinity)<br>        }<br>        .offset(x: <strong>showingMenu</strong> ? 200.0 : 0.0, y: 0)<br>    }<br>}</pre><p>showingMenu is a Boolean on which, the offset is depending upon. As you can see, when the user clicks the Menu Button, this value is toggled and it can present and hide the menu.</p><p>I’m just gonna go ahead and add a small snippet of code to give an animation to this transition-</p><p>.animation(.easeOut)</p><p>Let’s just add the rest of the Views to connect the Menus to.</p><pre>struct HomeView: View {<br>    <a href="http://twitter.com/State">@State</a> private var showingMenu = true<br>    var body: some View {<br>        ZStack {<br>            Color.black.edgesIgnoringSafeArea(<br>                .all)<br>            VStack(alignment: .leading) {<br>                Button(action: {self.showingMenu.toggle()}) {<br>                    Image(systemName: &quot;line.horizontal.3&quot;)<br>                        .foregroundColor(.white)<br>                }<br>                .frame(width: 50.0, height: 50.0)<br>                Spacer()<br>                Text(&quot;This Is Home&quot;)<br>                    .font(<br>                        .largeTitle)<br>                    .foregroundColor(<br>                        .white)<br>                    .frame(maxWidth: .infinity)<br>                Spacer()<br>            }.padding(.horizontal) .frame(maxWidth: .infinity)<br>        }<br>        .offset(x: showingMenu ? 200.0 : 0.0, y: 0)<br>        <strong>.animation(.easeOut)</strong><br>    }<br>}</pre><pre>struct ProfileView: View {<br>    <a href="http://twitter.com/State">@State</a> private var showingMenu = false<br>    var body: some View {<br>        ZStack {<br>            <br>            Color.red.edgesIgnoringSafeArea(<br>                .all)<br>            VStack(alignment: .leading) {<br>                Button(action: {self.showingMenu.toggle()}) {<br>                    Image(systemName: &quot;line.horizontal.3&quot;)<br>                        .foregroundColor(.white)<br>                }<br>                .frame(width: 50.0, height: 50.0)<br>                Spacer()<br>                Text(&quot;This Is Profile&quot;)<br>                    .font(<br>                        .largeTitle)<br>                    .foregroundColor(<br>                        .white)<br>                    .frame(maxWidth: .infinity)<br>                Spacer()<br>            }.padding(.horizontal) .frame(maxWidth: .infinity)<br>        }<br>        .offset(x: showingMenu ? 200.0 : 0.0, y: 0)<br>        <strong>.animation(.easeOut)</strong><br>    }<br>}</pre><pre>struct ChatView: View {<br>    <a href="http://twitter.com/State">@State</a> private var showingMenu = false<br>    var body: some View {<br>        ZStack {<br>            <br>            Color.blue.edgesIgnoringSafeArea(<br>                .all)<br>            VStack(alignment: .leading) {<br>                Button(action: {self.showingMenu.toggle()}) {<br>                    Image(systemName: &quot;line.horizontal.3&quot;)<br>                        .foregroundColor(.white)<br>                }<br>                .frame(width: 50.0, height: 50.0)<br>                Spacer()<br>                Text(&quot;This Is Chat&quot;)<br>                    .font(<br>                        .largeTitle)<br>                    .foregroundColor(<br>                        .white)<br>                    .frame(maxWidth: .infinity)<br>                Spacer()<br>            }.padding(.horizontal) .frame(maxWidth: .infinity)<br>        }<br>        .offset(x: showingMenu ? 200.0 : 0.0, y: 0)<br>        <strong>.animation(.easeOut</strong>)<br>    }<br>}</pre><pre>struct LogoutView: View {<br>    <a href="http://twitter.com/State">@State</a> private var showingMenu = false<br>        var body: some View {<br>            ZStack {<br>                <br>                Color.green.edgesIgnoringSafeArea(<br>                    .all)<br>                VStack(alignment: .leading) {<br>                    Button(action: {self.showingMenu.toggle()}) {<br>                        Image(systemName: &quot;line.horizontal.3&quot;)<br>                            .foregroundColor(.white)<br>                    }<br>                    .frame(width: 50.0, height: 50.0)<br>                    Spacer()<br>                    Text(&quot;This Is Logout&quot;)<br>                        .font(<br>                            .largeTitle)<br>                        .foregroundColor(<br>                            .white)<br>                        .frame(maxWidth: .infinity)<br>                    Spacer()<br>                }.padding(.horizontal) .frame(maxWidth: .infinity)<br>            }<br>            .offset(x: showingMenu ? 200.0 : 0.0, y: 0)<br>            <strong>.animation(.easeOut)</strong><br>        }<br>}</pre><p>In the ContentView we shall create a function to return a View needed based on Menu item selected.</p><pre>func selected(Menu: MenuContent) -&gt; some View {<br>    switch Menu.name {<br>    case &quot;Home&quot;:<br>        return AnyView(<strong>HomeView()</strong>)<br>        <br>    case &quot;Profile&quot;:<br>        return AnyView(<strong>ProfileView()</strong>)<br>        <br>    case &quot;Chat&quot;:<br>        return AnyView(<strong>ChatView()</strong>)<br>        <br>    case &quot;Logout&quot;:<br>        return AnyView(<strong>LogoutView()</strong>)<br>    default:<br>        return AnyView(<strong>HomeView()</strong>)<br>    }<br>}</pre><p>Finally, we should modify the Body of the ContentView to change screens on click of MenuCell.</p><pre>struct ContentView: View {<br>    var menu: [MenuContent] = menuContents<br>    <a href="http://twitter.com/State"><strong>@State</strong></a><strong> var menuItemSelected: MenuContent = menuContents[0]</strong><br>    var body: some View {<br>        ZStack {<br>            List(menu) { menuItem in<br>                MenuCell(menuItem: menuItem).onTapGesture {<br>                    <strong>self.menuItemSelected = menuItem</strong><br>                }<br>            }<br>            self.selected(Menu: <strong>menuItemSelected</strong>)<br>        }<br>    }<br>}</pre><p>With menuItemSelected being an @State var , everytime value in it changes, the ContentView will re-render itself and change the top view of the ZStack .</p><p>Final output will look something like this-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6_TvbSgqMEEpogzULgk5GA.gif" /><figcaption>Final Screen</figcaption></figure><p>This is one of the many ways that one can implement a Navigation Drawer in iOS, using SwiftUI. It has never been easier.</p><p>If anybody is interested, they can check out the full code at-</p><p><a href="https://github.com/sidjdev/NavigationDrawer">sidjdev/NavigationDrawer</a></p><p>Cheers!</p><figure><a href="http://buymeacoffee.com/sidjdev"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4ajjFwLjKin4nxFuxFhkQ.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=891663dd32d2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/creating-navigation-drawer-with-swiftui-891663dd32d2">Creating Navigation Drawer with SwiftUI</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>