<?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 Abhishek Ravi 🇮🇳 on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Ravi 🇮🇳 on Medium]]></description>
        <link>https://medium.com/@greenSyntax?source=rss-edc7d1e2341------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mDCyd8OtZQkZqSr2w9PXog@2x.jpeg</url>
            <title>Stories by Abhishek Ravi 🇮🇳 on Medium</title>
            <link>https://medium.com/@greenSyntax?source=rss-edc7d1e2341------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:15:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@greenSyntax/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[Environment in iOS]]></title>
            <link>https://medium.com/@greenSyntax/environment-in-ios-642438b86ce8?source=rss-edc7d1e2341------2</link>
            <guid isPermaLink="false">https://medium.com/p/642438b86ce8</guid>
            <category><![CDATA[xconfig]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Abhishek Ravi ]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 18:08:41 GMT</pubDate>
            <atom:updated>2024-07-26T18:09:43.572Z</atom:updated>
            <content:encoded><![CDATA[<h3>Objective</h3><p>If you’re supposed to build any production-ready application, you’ll always have to be futuristic about your app. Apart from the network layer, data layer, analytics layer, and deep link resolver, one thing is a must:<br>‘<em>set up an environment for your app’.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IUMUf6qMchOJjxKr0Ngig.png" /></figure><p>The app should have different environments, such as <em>Stage</em>, <em>Beta</em>, and <em>Production</em>. You can have as many environments as you want, but I always go with these three.</p><h3>Agenda</h3><p>So, the order will be like —</p><ol><li>First, create xconfigfiles — stage.xconfigand production.xconfig</li><li>Create Configuration(s) and attach theirxconfig file.</li><li>Now, create Schemes — Stage and Production and attach configuration.</li><li>Write AppConfiguration.swift which will have control over config keys.</li></ol><h3>Create Environment</h3><p>First, we’ve to create .xconfig file for Stage and Production Environment. I am assuming, you have these two only. You can have as many as you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfO_KDm6upMCFbRvCESzUg.png" /></figure><p>So, I created two xconfig file named — stage.xconfig and production.xconfig</p><p>In Stage Config File, I kept following keys</p><pre><br>BASE_URL= https:/$()/stg-app.greensyntax.io<br>SSL_PINNING = false<br>WORKSPACE_ID = 2435433</pre><p>And, with the same key on Production Config File,</p><pre>BASE_URL= https:/$()/app.greensyntax.io<br>SSL_PINNING = true<br>WORKSPACE_ID = 865435546</pre><p>Next, we have two mention these keys in Info.plist of your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e99g4icg2fBsuLX0VTQs7w.png" /></figure><p>Now, create stageand productionconfiguration and then attach their respective config file to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oi0ck-YXr7AK0-mpD_m_kw.png" /></figure><p>Next, we need to associate these xconfig files with their Schemes. <br>Let’s create Schemes then,</p><p>Click on New Scheme and Mention Your Environment . I have already created Production and Stage schemes for myself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAvG79ehKwLfKOOl460_jw.png" /></figure><p>After creating, make sure you have attached to the right configuration file. Say, the production scheme is attached to the production scheme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYh-W37BuiHEJugM9E4vLA.png" /></figure><p>Now, we are ready to access the value from the config file. For this, we will keep a single gateway class — AppConfiguration.swift</p><p>So, the responsibility of this class will be to read the value from the Active Configuration File.</p><pre>import Foundation<br><br>enum ConfigurationKey: String {<br>    case baseURL = &quot;BASE_URL&quot;<br>    case projectID = &quot;PROJECT_ID&quot;<br>    case sslPinning = &quot;SSL_PINNING&quot;<br>}<br><br>final class AppConfiguration {<br>    <br>    private static let infoDictionary: [String: Any] = {<br>        guard let dict = Bundle.main.infoDictionary else {<br>            fatalError(&quot;🔥 Info.plist is Missing from your Project&quot;)<br>        }<br>        return dict<br>    }()<br>    <br>    static func getBaseURL() -&gt; String {<br>        guard let baseURL = AppConfiguration.infoDictionary[ConfigurationKey.baseURL.rawValue] as? String else {<br>            fatalError(&quot;🔥 BASE_URL is missing in XCConfig File&quot;)<br>        }<br>        return baseURL<br>    }<br>    <br>    static func getProjectID() -&gt; String {<br>        guard let projectId = AppConfiguration.infoDictionary[ConfigurationKey.projectID.rawValue] as? String else {<br>            fatalError(&quot;🔥 PROJECT_ID is missing in XCConfig File&quot;)<br>        }<br>        return projectId<br>    }<br>    <br>    static func isSSLPinning() -&gt; Bool {<br>        guard let isSSLPinning = AppConfiguration.infoDictionary[ConfigurationKey.sslPinning.rawValue] as? Bool else {<br>            fatalError(&quot;🔥 SSL_PINNING is missing in XCConfig File&quot;)<br>        }<br>        return isSSLPinning<br>    }<br>}</pre><p>Here, getBaseURL(), getProjectID(), isSSLPinning() are the methods which are exposed to others. It will get value from *.xconfig the file.</p><h3>Conclusion</h3><p>Whether you are making any baby app or a production-ready app, it’s always good to have an Environment if you have API as your data provider. Along with that, It will also help you in CI/CD to create different flavors of Builds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=642438b86ce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a CocoaPod Package with XCFrameworks ]]></title>
            <link>https://medium.com/@greenSyntax/building-a-cocoapod-package-with-xcframeworks-0e4aaf029abd?source=rss-edc7d1e2341------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e4aaf029abd</guid>
            <category><![CDATA[xcframework]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[cocoapods]]></category>
            <dc:creator><![CDATA[Abhishek Ravi ]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 19:20:11 GMT</pubDate>
            <atom:updated>2024-07-19T19:31:27.769Z</atom:updated>
            <content:encoded><![CDATA[<h3>Objective</h3><p>Recently, I was given a task where I had to build a private library that our internal development team would use. And, it has a few constraints, our code won’t be exposed and no one can see the source code implementation. It will be distributed through cocoa pods in an abstract way (i.e. Private Distribution within our organization).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plycS4GbH6JB_HqZiZbuNA.png" /></figure><h3>Agenda</h3><p>We are going to build two XCFrameworks and then distribute both of them using Cocoapods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIEH3PgIWaPTC3X0J0A0RQ.png" /></figure><h3>Build XCFrameworks</h3><p>Open your code and choose the ‘<em>Framework</em>’ project. Make sure you enable Build Libraries for Distribution it as Yes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQru6wbXlw6kgM32JNspkg.png" /></figure><p>Now, we’re going to write a class that we’ll keep inside our framework — <strong>AuthenticationService.swift.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UVgbCySYL2Rrxa1AbHCdrw.png" /></figure><p>Here, we will just have some public methods that we will use by other apps. I will not write any implementation here (for obvious reasons).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*307SDCrP7VjqqsGGBQ8dIA.png" /></figure><p>If everything goes well, you won’t get any build errors and ready to make a distributable framework file— <strong>auth_library.xcframework</strong></p><p>Create a builder.sh and copy the following set of commands.</p><p>⚠️ You have to replace my <strong>scheme name </strong>with my “<strong>auth-library</strong>”. If you face any error while executing it on the <em>Terminal</em>, high chance that you’re messing with the scheme name.<br>So, this script will create two <strong>.xcarchive</strong> files where one is for Simulator and the other is for an iOS device, and then merge both the files into an xcframework.</p><pre>rm -rf build<br><br># For iOS Device<br>xcodebuild archive \<br>-scheme auth-library \<br>-sdk iphoneos \<br>-configuration Release \<br>-destination &#39;generic/platform=iOS&#39; \<br>-archivePath &#39;./build/auth-library.framework-iphoneos.xcarchive&#39; \<br>SKIP_INSTALL=NO \<br>BUILD_LIBRARIES_FOR_DISTRIBUTION=YES<br><br># For Simulators<br>xcodebuild archive \<br>-scheme auth-library \<br>-sdk iphoneos \<br>-configuration Release \<br>-destination &#39;generic/platform=iOS Simulator&#39; \<br>-archivePath &#39;./build/auth-library.framework-iphonesimulator.xcarchive&#39; \<br>SKIP_INSTALL=NO \<br>BUILD_LIBRARIES_FOR_DISTRIBUTION=YES<br><br># Create XCFramework<br>xcodebuild -create-xcframework \<br> -framework &#39;./build/auth-library.framework-iphonesimulator.xcarchive/Products/Library/Frameworks/auth_library.framework&#39; \<br>-framework &#39;./build/auth-library.framework-iphoneos.xcarchive/Products/Library/Frameworks/auth_library.framework&#39; \<br>-output &#39;./build/auth-library.xcframework&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiWIRol_G4lMGxm5PipCPA.png" /></figure><p>Finally, we have our xcframework file which we will distribute through cocoapod.</p><p>There is no need to create another framework, you can continue with a single framework if you want to.</p><p>Let&#39;s repeat and build an <strong><em>analytics-library.xcframework</em></strong> which will confirm the following class diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ot79AlxRNXj_4s2POaM3Q.png" /></figure><p>AnalyticsService.swift</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2z-7JznHzbSoEjK7G8KzMQ.png" /></figure><p>Finally, you’ve both the framework file with you. And, we can distribute these xc-framework files. The world is okay with this until they have to distribute N number of xc-framework files. Sometimes, you have a framework file which have some dependencies with it, so in that case you have to give all the package file(s) to the client which doesn&#39;t look good at all.</p><p>So, Cocoapods came as a solution, they offered xc-framework to be distributed via pod.</p><h3>Distribute XCframework via Pod</h3><p>Every cocoapod has a soul and that is the <em>.podspec</em> file in it. This file will decide how your pod will behave for the world. This is more of a package’s config file. So, we will create a <em>CoreLib.podspec </em>file.</p><p>First, we will create a directory and run touch CoreLib.podspec</p><pre>Pod::Spec.new do |spec|<br>  spec.name          = &#39;CoreLib&#39;<br>  spec.version       = &#39;1.0.1&#39;<br>  spec.summary       = &#39;Core Library for NoMansLand&#39;<br>  spec.description   = &#39;This is an Core Library which will help us in achieving nothing&#39;<br>  spec.homepage      = &#39;https://greensyntax.app&#39;<br>  spec.author        = { &#39;Abhishek Ravi&#39; =&gt; &#39;ab.abhishek.ravi@gmail.com&#39; }<br>  spec.license       = { :type =&gt; &#39;MIT&#39;, :file =&gt; &#39;LICENSE&#39; }<br>  spec.source        = { :git =&gt; &#39;https://github.com/greenSyntax/core-lib.git&#39;, :tag =&gt; spec.version.to_s }<br>  spec.swift_version = &#39;5.0&#39;<br>  spec.ios.deployment_target = &#39;13.0&#39;<br><br>  spec.ios.vendored_frameworks = [<br>    &quot;Frameworks/auth_library.xcframework&quot;,<br>    &quot;Frameworks/analytics_library.xcframework&quot;<br>  ]<br>end</pre><p>Except for <em>‘</em><strong><em>spec.ios.vendored_frameworks</em></strong><em>’, </em>I think every other specs property is self-explanatory. So, we use <strong><em>vendored_frameworks </em></strong>only we have to specify any framework binary files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYbgP632McMEQvVm-H3W5Q.png" /></figure><p>Next, I’ll try to run pod lib lintto verify if there is nothing wrong with my podspec file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdOmn7gFtpl4AfaDbL-WZQ.png" /></figure><h3>Let’s try your package</h3><p>First, we will create a test app and then make a Podfile — pod init</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMNfklnkhVDHu3lvBn9x4g.png" /></figure><p>And, you will install the packages by pod install After that, we will consume it in our project. First, import the packages by name and try to call the Service Class we made earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZraH9PvOD_CvhG7M9AAYw.png" /></figure><h3>Source Code</h3><p>I have attached ‘<em>CoreLib</em>’ <a href="https://github.com/greenSyntax/core-lib-example">Github Repository </a>here. You can check branches for xc-framework sample projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e4aaf029abd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Charles Proxy : Developer’s Guide]]></title>
            <link>https://medium.com/@greenSyntax/charles-proxy-developers-guide-81f59bb71466?source=rss-edc7d1e2341------2</link>
            <guid isPermaLink="false">https://medium.com/p/81f59bb71466</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[charles-proxy]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Abhishek Ravi ]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 09:56:38 GMT</pubDate>
            <atom:updated>2023-04-14T09:56:38.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>Charles Proxy : Developer’s Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGCgaYvQYXzCA313Zaquxg.png" /></figure><h4>Objective</h4><p>If I have to recommend <strong>must-have-developer-tool</strong> that every developer should have (or, learn) then <em>Charles</em> will be one of them. And, for a mobile developer it’s a must tool which you can have in your toolkit bag. I realised it’s true power very late in my development career, earlier I used it as HTTP Network Monitoring Tool, but it’s definitely more than this.<br>Yes, I am totally in for purchasing this product. And, we need to takeout some time and thanks <em>Karl von Randow</em> for this — For Creating this Primer✌️</p><h4>Agenda</h4><ol><li>Setup Charles</li><li>Monitor HTTP Traffic</li><li>Mock Response</li><li>Breakpoint</li><li>Rewrite</li><li>Throttling</li><li>Repeat</li><li>Troubleshooting Charles</li></ol><h4>Setup</h4><ol><li>Install Charles from <a href="https://www.charlesproxy.com/download/">Official Website</a> and <em>Start</em> <em>Recoding — Top Red</em> Button.</li><li>Next, you need to do is to install <em>Certificates</em> on your mac and physical device (iOS or android).</li></ol><p><strong>🐞 Note</strong>: Here, I will be considering my phone as iPhone, but android has almost same steps.</p><p>Install Certificate on Mac —</p><p><strong>Go to Charles &gt; Help &gt; SSL Proxy &gt; Install Certificate</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*gHln0mb1nYF6ttXKLvYIpg.png" /></figure><p>And, by clicking over — Save Charles Root Certificate. You get a *.cer file, which you need to double click to put it in Keychain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNIez53DTWef8j6_7ZqyPQ.png" /></figure><p>Now, its time to install <em>certificate</em> on your iPhone—</p><ol><li>Go to Charles &gt; Help &gt; Local IP and remember this IP 😅</li><li>Take out your iPhone, Open Settings, connect to the same Wifi Network where your Mac is on —<em> Settings &gt; Wifi &gt; Tap on the (i) of Connected Wifi &gt; Configure Proxy &gt; Select Manual</em></li><li>Server : Same <strong>IP which you got in <em>step-1</em></strong><br>Port: <strong>8888</strong><br>Authentication: <strong>false</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*-bQyDNErH-Rmw56z5WJeKQ.png" /></figure><ol><li>After that, you will get an alert on your Mac, to <em>allow</em> the device is being proxied. Please select allow else, your device won’t be monitored. <br>After being connect to the same network.</li><li>Go to safari and open — <a href="https://chls.pro/ssl">https://chls.pro/ssl</a> (make sure, you install certificate when you iPhone is proxied with Charles ⚠️).</li><li>You will get a pop-up something like — This website is trying to download a configuration profile. Do you want to allow this? <strong>Allow </strong>for the time being. And, then you will get Profile Downloaded ✅</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*GJQPmdojT2iA5AkIW8QDCw.png" /></figure><p>4. Go to <em>Settings &gt; General &gt; VPN &amp; Device Management &gt;</em> There you will see a Downloaded Profile — <em>Charles Proxy Custom Root Certificate , </em>tap over it and Install the certificate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*h9sb3QF5a5wWo1Fuu4lutQ.png" /></figure><p>5. Now, you will see it’s successfully installed and lied under — <em>Configuration Profiles</em>.</p><p>6. One more step is left, Go back to Settings &gt; General &gt; About &gt; Certificate Trust Settings &gt; Turn On the Charles Root Custom Certificate (by default, it’s turned off)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*E06lMgxTXu5zFcF9XKyxVQ.png" /></figure><p>7. Finally, you are Done with Charles Setup 🚀</p><h4>Monitor HTTP Traffic</h4><p>If your Charles has been established, then you can see the network traffic of your device. Here, I was trying to open <a href="https://jsonplaceholder.typicode.com/users"><em>https://jsonplaceholder.typicode.com</em>/users </a>in the safari, and then you will see traffic in tree form.</p><p>Meanwhile, Right click on <a href="https://jsonplaceholder.typicode.com/">https://jsonplaceholder.typicode.com</a> from Charle’s Tree and select <em>Enable SSL Proxying</em> for this hostname. <br><strong>Note:</strong> If you won’t do this step, then your can’t read your traffic data, as it will be in encrypted form — HTTPS SSH/TLS is the culprit ⚠️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Ymujg68aAgvWeTY17QcvQ.png" /></figure><p>As you can see, <em>Overview </em>tab has the metadata like, Hostname, DNS Address, HTTP Response Code, HTTP Method, Protocol name, all the timestamp which you will need in metric calculation — response time, latency, handshake timestamp.</p><p>Next one is <em>Request</em> tab, which will show the request HTTP data. Since, this is a GET request, so won’t see any body here except the headers and HTTP params.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkvULnMjOhp_-VxF_U9GMQ.png" /></figure><p>And, in <em>Response </em>tab, you will find the HTTP response. It will have the headers, HTTP body and Raw HTTP data (if, you are interested in it). For me, JSON text is all I need, coz this is where the HTTP Body is preety printed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_m1QiK64wIO42cAWPTRj5g.png" /></figure><h4>Mock Response</h4><p>I mock response, you will learn two ways to mock your response — <em>Local</em> and <em>Remote</em>.</p><p>Say, you are a mobile developer and you are working on your app where you are getting the JSON data of a user from a GET API — (<a href="https://jsonplaceholder.typicode.com/users/1"><em>https://jsonplaceholder.typicode.com/users/1</em></a>), but you want to reproduce a weird case with some ill value.</p><p>Positive Expected Response:</p><pre>{<br>&quot;id&quot;: 1,<br>&quot;name&quot;: &quot;Leanne Graham&quot;,<br>&quot;username&quot;: &quot;Bret&quot;,<br>&quot;email&quot;: &quot;Sincere@april.biz&quot;,<br>&quot;address&quot;: {<br>&quot;street&quot;: &quot;Kulas Light&quot;,<br>&quot;suite&quot;: &quot;Apt. 556&quot;,<br>&quot;city&quot;: &quot;Gwenborough&quot;,<br>&quot;zipcode&quot;: &quot;92998-3874&quot;,<br>&quot;geo&quot;: {<br>&quot;lat&quot;: &quot;-37.3159&quot;,<br>&quot;lng&quot;: &quot;81.1496&quot;<br>}<br>},<br>&quot;phone&quot;: &quot;1-770-736-8031 x56442&quot;,<br>&quot;website&quot;: &quot;hildegard.org&quot;,<br>&quot;company&quot;: {<br>&quot;name&quot;: &quot;Romaguera-Crona&quot;,<br>&quot;catchPhrase&quot;: &quot;Multi-layered client-server neural-net&quot;,<br>&quot;bs&quot;: &quot;harness real-time e-markets&quot;<br>}<br>}</pre><p>Now, you want a response where <strong>name</strong> is <em>null</em>, <strong>address</strong> is <em>empty</em> (just to ensure app won’t malfunction if such response come to client).<br>So, I made a JSON like this —</p><pre>{<br>&quot;id&quot;: 1,<br>&quot;name&quot;: null,<br>&quot;username&quot;: &quot;Bret&quot;,<br>&quot;email&quot;: &quot;Sincere@april.biz&quot;,<br>&quot;address&quot;: {},<br>&quot;phone&quot;: &quot;1-770-736-8031 x56442&quot;,<br>&quot;website&quot;: &quot;hildegard.org&quot;,<br>&quot;company&quot;: {<br>&quot;name&quot;: &quot;Romaguera-Crona&quot;,<br>&quot;catchPhrase&quot;: &quot;Multi-layered client-server neural-net&quot;,<br>&quot;bs&quot;: &quot;harness real-time e-markets&quot;<br>}<br>}</pre><p>Charles enable you to mock the response of <a href="https://jsonplaceholder.typicode.com/users/1"><em>https://jsonplaceholder.typicode.com/users/1</em></a><em> by Map Locale.</em></p><p><strong>Charles &gt; Tools &gt; Map Local, enable the Map Local and Add.</strong></p><p>And, while mocking you need to select the *.json file path which will be your source of truth. I have create one by the <em>mock_response.json . </em>This JSON will override the server’s JSON response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQRphzC7YINGNKl_nC-M4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDIvHmulMAHzfrbCFaqoxg.png" /></figure><p>Now, when I request for <a href="https://jsonplaceholder.typicode.com/users/1"><em>https://jsonplaceholder.typicode.com/users/1</em></a><em> </em>then I will get the Mocked JSON response instead of actual response which server is serving. Let me show it you —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uiltXrzbkJp62qZnHsz9Mw.png" /></figure><p><strong>📕 Notebook: When you want to reproduce a very peculiar API response, then you can use this Map Local and serve it to client.</strong></p><p>And, there is other alternative for this — <strong><em>Map Remote</em></strong><em>, as name suggest </em>it will route a API path to different API path.<br>Say, you want to redirect <em>/posts/1 </em>to /users/1 API. Whenever user is trying to request for https://jsonplaceholder.typicode.com/posts/1, it will further redirected to https://jsonplaceholder.typicode.com/users/1 . I hardly used this in my day-to-day life, but now you know what to do if anything similar comes to you.</p><p><strong>Charles &gt; Tools &gt; Map Remote &gt; Enable &gt; Add</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNa_OT5TI_P8GscNiB0Y-g.png" /></figure><h4><strong>Breakpoint</strong></h4><p>Breakpoint is something which will help you in altering the HTTP request or response. By altering i mean — Alter Headers, Body anything you want.</p><p>To enable breakpoint, you have to —</p><p><strong>Charles &gt; Proxy &gt; Breakpoint Settings &gt; Enable Breakpoint &gt; Add</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Gvz0zGqKP7kMIGL-dr4-w.png" /></figure><p>Here, I have added breakpoint for jsonplaceholder.typicode.com for every request and response. This is behave like an interceptor. <br>Each time, you create a HTTP Request, Charles will pop up a breakpoint for the request where you can alter the HTTP request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEVg4LcYTNVHjz-1V1AetA.png" /></figure><p>Here, I won’t change in the request as of now, so I will select <strong>Execute</strong>. Soon, you will get another Breakpoint window which will show Edit Response —</p><p>Here, I will change the <strong>username</strong> in JSON to <strong>abhishekRavi</strong> and tap on Execute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eYJlNp_Hbr__SENcej_Dw.png" /></figure><p>Yes, now you can see the magic. Client will be server with a username where value is <strong>abhishekRavi.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGTMEv74zfZaWe_r5am18A.png" /></figure><p><strong>📕 Notebook: You can use breakpoint to modify HTTP request/ response, be it headers, status code, JSON body or anything. You are free to do anything.</strong></p><h4><strong>Rewrite</strong></h4><p>It is more of a improved version of Breakpoint. Rewrite is more of a pre-defined breakpoint. You can set rule of certain API endpoint.</p><p><strong>Charles &gt; Tools &gt; Rewrite &gt; Enable &gt; Add &gt; Create Location and Action</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yx8vt9UrasT6Qicq0c3P2A.png" /></figure><p>Here, I have create a JSOnPlaceholder rule and mentioned the Remote Location or API Path, whatever you want to say and then in Body I have asked to rename ‘<em>title’</em> to <em>‘t00tle’.</em></p><p>Same, you can do it with Headers and Body. I can set regex (If you are god’s favourite child and you know how to write regex then it’s for you 😄) .<br>Here, I tried to set a rule where HTTP Status code turn from 200 to 400.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HtET-U1PRmW-18bFOAvk4g.png" /></figure><p><strong>📕 Notebook: If you want to repeat some task, then you can write rule for such task.</strong></p><h4>Throttling</h4><p>This is something which is very usefull for App Developer, say you want some API to have high latency and want to test how your app behaves. You can configure the Charles Throttler, just to play with the response time and bandwith. <br>First, set the Throttler Settings and then start the Throttler. I always go with the <em>56Kbps Modem</em> preset.</p><p><strong>Charles &gt; Proxy &gt; Start Throttler</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4ba7WZEIUC1gd2j4nymXw.png" /></figure><h4>Repeat</h4><p>Say, you know a API which is failing intermittently and you want to test the load of the API, the Charles have a feature called Repeat which will allow you to call API n-number of times in concurrent fashion.</p><p>By Right clicking on the API endpoint, and select Repeat Advance —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AyArOts9M77y198ClB5wRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tnh3Q5hpFkSZo1INn5Vt2A.png" /></figure><p>And, you can configure your repeat settings —</p><p>Say Iteration will be 100 and Concurrency will be 3 which is equivalent to — You will hit 100 HTTP API Requests in a batch of 3 request each time.</p><p><strong>📕 Notebook: Mostly I use this to load test the API, if it’s responding with 2xx or not.</strong></p><h4>Troubleshoot</h4><ol><li><strong>Can’t Install the SSL Certificate when I visit Charles Website</strong></li></ol><p>First, you need to check if your iPhone and Mac are on same Wifi Network and your have configured<em> Manual Proxy </em>on your iPhone. Refer <em>Setup</em> section of this article.<br>Second, still you are not getting the pop-up to download the Profiles then you need to change your IP Address from Mac Settings &gt; <em>Network Preference &gt; Advance &gt; TCP/IP &gt; Renew DHCP Lease</em> .</p><p><strong>2. Response is always in Encrypted for me.</strong></p><p>First, check if you have Enabled SSL Proxying for the Hostname. You can verify by right clicking over the host name from tree and check if it’s Enable SSL Proxying (i.e. you haven’t enabled it yet) or Disabled SSL Proxy (i.e. it’s already been enabled). Or, you can verify from Overview —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HB_DgvJ0YBZTKxCNElZpdQ.png" /></figure><p>Second, you can delete and reinstall your certificate from Phone Setting &gt; General &gt; VPN &amp; Device Management &gt; Select Charles Profile &gt; Remove Profile. Yes, just do a fresh start.</p><h4>Conclusion</h4><p>Charles is a proxy application which will sit between the client and server &amp; help you to monitor the HTTP traffic. You can manipulate the request and response as per your need. There are way more features than we have discussed above. You can try <em>Proxyman</em> as an alternative of Charles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81f59bb71466" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UIKit Component Styling in iOS]]></title>
            <link>https://medium.com/@greenSyntax/uikit-component-styling-in-ios-ae218ae4823e?source=rss-edc7d1e2341------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae218ae4823e</guid>
            <category><![CDATA[ios-design-themes]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-ui-design-tips]]></category>
            <dc:creator><![CDATA[Abhishek Ravi ]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 20:57:05 GMT</pubDate>
            <atom:updated>2023-04-06T09:07:30.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jYg1C9eqVHO05bWBjzWtlw.png" /></figure><h4>Objective</h4><p>If you have done any web development then you are aware of CSS and how developer cry over it 😂. But, you know — Styling is very important for any front end application. Be it mobile app or any web app, you should always follow a consistent design for your UI &amp; styling will help you in achieving this. If not, then you can ask your designer to make it consistent. In design, we should follow same font, consistent weight across the app, colour-theory should be same, padding, container view outside margin.</p><p>If you have worked on Android, they have pretty good convention to follow the fonts, colours, style — separate files for each. <br>But, in iOS people hardly follow any convention. How I got to know about this — Few years back, I was going through one of my friend Mukesh’s code and I saw this styling thing which he does in his project. I was like a <em>Eureka</em> moment for me.</p><h4>Agenda</h4><p>Here, I will try to copy Uber UI Design Theory for <em>Login</em> and <em>Reset Password</em> Module. We will try to create component which will be used across the app.</p><ol><li>Create a UITextField Component</li><li>Create a UILabel Component</li><li>Create UIButton Component</li><li>Create UIFont Component</li><li>Create UIColor Component</li></ol><p>Here, I have just created component for these UIKit controls, you explore more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*9fLU1_E_zWjTqackx95ILQ.png" /></figure><p>And, I follow this convention of starting component name with App, you can follow any prefix, there is no hard and fast rule for this. Usually, people follow their company’s initials (only if, you’re less creative with your naming convention) 😄</p><h4>AppFont</h4><p>Any design theory starts with the font and yes, it’s a very integral part of UI, it sets the visual tone. Let’s dive into it. <br>Either your UI Designer will give you the font, or you something for yourself from Google Fonts. I have chose <em>Montserrat </em>for myself.</p><p>So, first you need to download the *.ttf file and then import in your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*X7UwXiexTHH6pQfSATh8vA.png" /></figure><p>After importing the font file, you need to specify in your <em>Info.plist</em> file that, you’re using external font for this project—</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br>    &lt;key&gt;UIAppFonts&lt;/key&gt;<br>    &lt;array&gt;<br>        &lt;string&gt;Montserrat-Regular.ttf&lt;/string&gt;<br>        &lt;string&gt;Montserrat-Medium.ttf&lt;/string&gt;<br>        &lt;string&gt;Montserrat-Bold.ttf&lt;/string&gt;<br>        &lt;string&gt;Montserrat-Thin.ttf&lt;/string&gt;<br>        &lt;string&gt;Montserrat-Italic.ttf&lt;/string&gt;<br>    &lt;/array&gt;<br> &lt;key&gt;UIApplicationSceneManifest&lt;/key&gt;<br> &lt;dict&gt;<br>  &lt;key&gt;UIApplicationSupportsMultipleScenes&lt;/key&gt;<br>  &lt;false/&gt;<br>  &lt;key&gt;UISceneConfigurations&lt;/key&gt;<br>  &lt;dict&gt;<br>   &lt;key&gt;UIWindowSceneSessionRoleApplication&lt;/key&gt;<br>   &lt;array&gt;<br>    &lt;dict&gt;<br>     &lt;key&gt;UISceneConfigurationName&lt;/key&gt;<br>     &lt;string&gt;Default Configuration&lt;/string&gt;<br>     &lt;key&gt;UISceneDelegateClassName&lt;/key&gt;<br>     &lt;string&gt;$(PRODUCT_MODULE_NAME).SceneDelegate&lt;/string&gt;<br>     &lt;key&gt;UISceneStoryboardFile&lt;/key&gt;<br>     &lt;string&gt;Main&lt;/string&gt;<br>    &lt;/dict&gt;<br>   &lt;/array&gt;<br>  &lt;/dict&gt;<br> &lt;/dict&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><p>Now, I will create a AppFont file with following code. You can structure as you wish, but our prime objective here will be —</p><p>This class will decide for the app that, what set of fonts &amp; weight you are going to use. You can expose as many method as you want. Naming Convention is also upto you, I have followed mine.</p><pre>import UIKit<br><br>extension UIFont {<br>    <br>    private enum CustomFont: String {<br>        case book = &quot;Montserrat-Regular&quot;<br>        case italic = &quot;Montserrat-Italic&quot;<br>        case thin = &quot;Montserrat-Thin&quot;<br>        case medium = &quot;Montserrat-Medium&quot;<br>        case bold = &quot;Montserrat-Bold&quot;<br>    }<br>    <br>    static func appFontRD(ofSize size: CGFloat, weight: UIFont.Weight = .regular) -&gt; UIFont {<br>        var font = UIFont(name: CustomFont.book.rawValue, size: size)<br>        switch weight {<br>        case .ultraLight:<br>            font = UIFont(name: CustomFont.thin.rawValue, size: size)<br>        case .thin:<br>            font = UIFont(name: CustomFont.thin.rawValue, size: size)<br>        case .light:<br>            font = UIFont(name: CustomFont.thin.rawValue, size: size)<br>        case .regular:<br>            font = UIFont(name: CustomFont.book.rawValue, size: size)<br>        case .medium:<br>            font = UIFont(name: CustomFont.medium.rawValue, size: size)<br>        case .semibold:<br>            font = UIFont(name: CustomFont.medium.rawValue, size: size)<br>        case .bold:<br>            font = UIFont(name: CustomFont.bold.rawValue, size: size)<br>        case .heavy:<br>            font = UIFont(name: CustomFont.bold.rawValue, size: size)<br>        case .black:<br>            font = UIFont(name: CustomFont.bold.rawValue, size: size)<br>        default:<br>            font = UIFont(name: CustomFont.book.rawValue, size: size)<br>        }<br>        guard let retValue = font else {<br>            return .systemFont(ofSize: size, weight: weight)<br>        }<br>        return retValue<br>    }<br>    <br>    static func boldAppFontRD(ofSize size: CGFloat) -&gt; UIFont {<br>        return self.appFontRD(ofSize: size, weight: .bold)<br>    }<br>    <br>    static func italicAppFontRD(ofSize size: CGFloat) -&gt; UIFont {<br>        guard let retValue = UIFont(name: CustomFont.italic.rawValue, size: size) else {<br>            return .italicSystemFont(ofSize: size)<br>        }<br>        return retValue<br>    }<br>}<br><br>class AppFont {<br>    <br>    static let shared = AppFont()<br>    <br>    public var headingSemibold: UIFont {<br>        return UIFont.appFontRD(ofSize: 32, weight: UIFont.Weight.semibold)<br>    }<br>    <br>    public var headingRegular: UIFont {<br>        return UIFont.appFontRD(ofSize: 32, weight: UIFont.Weight.regular)<br>    }<br>    <br>    public var headlineSemibold: UIFont {<br>        return UIFont.appFontRD(ofSize: 24, weight: UIFont.Weight.semibold)<br>    }<br>    <br>    public var headlineRegular: UIFont {<br>        return UIFont.appFontRD(ofSize: 24, weight: UIFont.Weight.regular)<br>    }<br>    <br>    public var titleSemibold: UIFont {<br>        return UIFont.appFontRD(ofSize: 20, weight: UIFont.Weight.semibold)<br>    }<br>    <br>    public var titleRegular: UIFont {<br>        return UIFont.appFontRD(ofSize: 20, weight: UIFont.Weight.regular)<br>    }<br>    <br>    public var subHeadingSemibold: UIFont {<br>        return UIFont.appFontRD(ofSize: 16, weight: UIFont.Weight.semibold)<br>    }<br>    <br>    public var subHeadingRegular: UIFont {<br>        return UIFont.appFontRD(ofSize: 16, weight: UIFont.Weight.regular)<br>    }<br>    <br>    public var subHeadingMedium: UIFont {<br>        return UIFont.appFontRD(ofSize: 16, weight: UIFont.Weight.medium)<br>    }<br>    <br>    public var bodySemibold: UIFont {<br>        return UIFont.appFontRD(ofSize: 14, weight: UIFont.Weight.semibold)<br>    }<br>    <br>    public var bodyRegular: UIFont {<br>        return UIFont.appFontRD(ofSize: 14, weight: UIFont.Weight.regular)<br>    }<br>    <br>    public var captionSemibold: UIFont {<br>        return UIFont.appFontRD(ofSize: 12, weight: UIFont.Weight.semibold)<br>    }<br>    <br>    public var captionRegular: UIFont {<br>        return  UIFont.appFontRD(ofSize: 12, weight: UIFont.Weight.regular)<br>    }<br>    <br>    public var bodyMedium: UIFont {<br>        return UIFont.appFontRD(ofSize: 14, weight: UIFont.Weight.medium)<br>    }<br>    <br>    public var headlineMedium: UIFont {<br>        return UIFont.appFontRD(ofSize: 32, weight: UIFont.Weight.medium)<br>    }<br>    <br>    public var subHeadlineMedium: UIFont {<br>        return UIFont.appFontRD(ofSize: 24, weight: UIFont.Weight.medium)<br>    }<br>    <br>    public var bodyBook: UIFont {<br>        return UIFont.appFontRD(ofSize: 16)<br>    }<br>    <br>    public var headlineBook: UIFont {<br>        return UIFont.appFontRD(ofSize: 24)<br>    }<br>    <br>    public var subHeadlineBook: UIFont {<br>        return UIFont.appFontRD(ofSize: 24)<br>    }<br>    <br>    public func custom(_ size:CGFloat ,_ weight: UIFont.Weight) -&gt; UIFont {<br>        return UIFont.appFontRD(ofSize: size, weight: weight)<br>    }    <br>}<br></pre><p>And, when I am going to set my font to any UI Component, I will be like —</p><pre>myLabel.font = AppFont.shared.headlineBook</pre><p><strong>🍀 Advantage</strong> — Say, in near future Product team or Designers have decided to change the font, then you will have a single set of class where you have to do the changes. Yes, you’re right — <em>Single Responsibility Principle</em> ✌️</p><h4>AppLabel</h4><p>Label is like a cell in human body, you are bound to have this component in your project, it’s better to create a UI component for this.</p><pre>class AppLabel: UILabel {<br>    <br>    override init(frame: CGRect) {<br>        super.init(frame: frame)<br>        stupUI()<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        super.init(coder: coder)<br>        stupUI()<br>    }<br>    <br>    private func stupUI() {<br>        self.font = AppFont.shared.bodyMedium<br>    }<br>    <br>    func setSize(of size:CGFloat, of weight: UIFont.Weight) {<br>        self.font = AppFont.shared.custom(size, weight)<br>    }<br>    <br>}</pre><p>Here, I have just assigned the font for my label component, you can extend this class as per your need, be it colour, spacing or anything.<br>And, whenever you’re creating your UILabel, go to File Inspector and assign <em>AppLabel</em> to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*3BRij23dEyZHBHLE7_5Asg.png" /></figure><h4>AppButton</h4><p>Button is also one of the essential UI component.I personally, believes button shouldn’t have more than four states. So, in my case I have made enum of the States — primary and secondary.</p><p>You can have as multiple state, like — active, inactive, disabled, default and loading.</p><p>For Loading state, I have exposed a <em>isLoading</em> property (I know, it be under the enum).</p><pre>import UIKit<br><br>enum ButtonState {<br>    case primary<br>    case secondary<br>}<br><br>class AppButton: UIButton {<br>    <br>    private let activityIndicator = UIActivityIndicatorView(style: .medium)<br>    private var defaultStyle: ButtonState = .primary<br>    <br>    var isLoading: Bool = false {<br>        didSet {<br>            updateView()<br>        }<br>    }<br>    <br>    override init(frame: CGRect) {<br>        super.init(frame: frame)<br>        intialize()<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        super.init(coder: coder)<br>        intialize()<br>    }<br>    <br>    private func intialize() {<br>        self.titleLabel?.font = AppFont.shared.custom(16, .bold)<br>        self.layer.cornerRadius = 2.0<br>        self.setStyleState(self.defaultStyle)<br>        <br>        // Indicator<br>        addSubview(activityIndicator)<br>        activityIndicator.translatesAutoresizingMaskIntoConstraints = false<br>        NSLayoutConstraint.activate([<br>            activityIndicator.centerXAnchor.constraint(equalTo: self.centerXAnchor),<br>            activityIndicator.centerYAnchor.constraint(equalTo: self.centerYAnchor)<br>        ])<br>    }<br>    <br>    private func updateView() {<br>        if isLoading {<br>            activityIndicator.startAnimating()<br>            self.titleLabel?.alpha = 0<br>            self.titleLabel?.layer.opacity = 0<br>            self.imageView?.alpha = 0<br>            self.titleLabel?.isHidden = true<br>            self.titleLabel?.textColor = UIColor.clear<br>            isEnabled = false<br>        } else {<br>            activityIndicator.stopAnimating()<br>            self.titleLabel?.alpha = 1<br>            self.titleLabel?.layer.opacity = 1<br>            self.imageView?.alpha = 1<br>            self.titleLabel?.textColor = UIColor.white<br>            self.titleLabel?.isHidden = false<br>            isEnabled = true<br>        }<br>    }<br>    <br>    func setStyleState(_ state: ButtonState) {<br>        if state == .primary {<br>            self.setTitleColor(UIColor.white, for: .normal)<br>            self.backgroundColor = UIColor.black<br>            self.layer.borderColor = UIColor.black.cgColor<br>            self.layer.borderWidth = 1.5<br>            self.defaultStyle = .primary<br>        } else {<br>            self.setTitleColor(UIColor.black, for: .normal)<br>            self.backgroundColor = UIColor.white<br>            self.defaultStyle = .secondary<br>            self.layer.borderWidth = 1.5<br>            self.layer.borderColor = UIColor.black.cgColor<br>        }<br>    } <br>}</pre><p>So, both the primary and secondary button state look like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*1kJtQ4uuHNduxaG21YMP7Q.png" /></figure><p>You’re free to extend the class as per your need. And, please do comment if you find any abusive code 😅</p><p>And, you just need to assign your UIButton with AppButton class in <em>file inspector</em><strong>.</strong></p><h4>AppTextField</h4><p>Here, I haven’t played enough with UITextField. I just assigned few UI properties like border colour and text colour.</p><pre>import UIKit<br><br>class AppTextField: UITextField {<br>    <br>    override init(frame: CGRect) {<br>        super.init(frame: frame)<br>        setupUI()<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        super.init(coder: coder)<br>        setupUI()<br>    }<br>    <br>    private func setupUI() {<br>        let borderWidth = CGFloat(2.0)<br>        self.layer.borderColor = UIColor.darkGray.cgColor<br>        self.layer.frame = CGRect(x: 0, y: self.frame.size.height - borderWidth, width: self.frame.size.width, height: self.frame.size.height)<br>        self.layer.borderWidth = borderWidth<br>        self.textColor = UIColor.darkGray<br>        self.backgroundColor = UIColor.white<br>        self.font = AppFont.shared.bodyMedium<br>        self.attributedPlaceholder = NSAttributedString(<br>            string: self.placeholder ?? &quot;&quot;,<br>            attributes: [NSAttributedString.Key.foregroundColor: UIColor.darkGray]<br>        )<br>        self.layer.masksToBounds = true<br>        <br>    }<br>    <br>    override func textRect(forBounds bounds: CGRect) -&gt; CGRect {<br>        return CGRect(x: bounds.origin.x + 16, y: bounds.origin.y + 16, width: bounds.size.width - 20, height: bounds.size.height - 30 )<br>    }<br>    <br>    override func editingRect(forBounds bounds: CGRect) -&gt; CGRect {<br>        return self.textRect(forBounds: bounds)<br>    }<br>}</pre><p>And, Text Field will look something like this if you assign AppTextField —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*VSMCOF1CnlVlerbX_WOG9A.png" /></figure><h4>AppColor</h4><p>Yes, colours need to be under single class, you shouldn’t be allowed to consume colour directly using <em>UIColor.black</em></p><p>This will also helps you in future code changes if re-designing your UI comes up. Usually, designer have their colour pallet for the UI design.</p><p>Yes, I have directly consumed <em>UIColor.black</em> or <em>UIColor.white</em> in my code snippet. My Bad, I have pushed the fix, you can checkout from the Github.</p><pre>extension UIColor {<br>    static let appBlack = UIColor.black<br>    static let appWhite = UIColor.white<br>    static let appDarkGray = UIColor.darkGray<br>}</pre><h4>🌎 Source Code</h4><p><a href="https://github.com/greenSyntax/ios-app-styling/tree/main/ios-app-theme">ios-app-styling/ios-app-theme at main · greenSyntax/ios-app-styling</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae218ae4823e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Cell in UITableView]]></title>
            <link>https://medium.com/@greenSyntax/dynamic-cell-in-uitableview-2c779b8357e0?source=rss-edc7d1e2341------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c779b8357e0</guid>
            <category><![CDATA[uitableviewcell]]></category>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[Abhishek Ravi ]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 19:47:24 GMT</pubDate>
            <atom:updated>2023-04-04T19:59:44.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*FF7z3Bj8jfZLu21zYSwbcw.png" /></figure><h4>Objective</h4><p>For any iOS Developer, UITableView is just like a staple food. Whatever cuisine you try, ultimately you will fall for the UITableView whenever you are building any UI. Complexity comes up when you have to handle different type of cells with different data source. Due to this, your <em>cellForRowAtIndexPath(:_)</em> got cluttered and smelly.</p><p>Say, for the following UI you have three custom cells and in future you may get another type of cell which may come in between or end (order of cell could be anything). It could be anything, so you have write your code in such a way that it ‘ll handle without or with dev effort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFGsO0Puz9-QTebG1m0G8g.png" /></figure><p>Some of us may write something like — <em>indexPath.row == 0</em><br>And, if you are the one of them, then this article will help you in improving your code —</p><pre>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>  if indexPath.row == 1 {<br>    // Load HeaderCell<br>    let cell = tableView.dequeueReusableCell(withIdentifier: &quot;HeaderCell&quot;) as! HeaderCell<br>    // TODO: <br>  } else if indexPath.row == 2 {<br>    // Load Thumbnail Cell<br>    let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ImageThumbnailCell&quot;) as! ImageThumbnailCell<br>    // TODO:<br>  } else if indexPath.row == 3 {<br>    // Load Content Cell<br>    let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ContentCell&quot;) as! ContentCell<br>    // TODO:<br>  }<br>}</pre><h4>Enum’s Associated Value</h4><p>Here, we are going to use enum associated value. This is going to be the heart of it. So, what is associated value in an enum ?</p><p>So, You can bundle some <em>type</em> with enum’s case. AFAIK, in other languages enum doesn’t support such thing like associate value. But, in Swift you can attach <em>Associated Value</em> which is populated at runtime. Say, you have <strong>MediaType</strong> for an app —</p><pre>enum MediaType {<br>  case netflix(link: URL)<br>  case amazonPrime(link: URL)<br>  case local(link: URL)<br>  case youtube(videoId: String)<br>  case remoteBucket(mediaId: String)<br>}</pre><p>And, when you consume this enum, you have to pass the associated value along with the case.</p><pre>var selectedMedia: MediaType = MediaType.netflix(URL(string:&quot;https://www.netflix.com/watch/81318083?source=35&quot;)!)</pre><p>So, whenever we need to design our UITableView, then very first thing you do is to distinguish <em>Type of Cell</em> and consider it as a case in enum.<br>For us, our <em>enum</em> will be something like this —</p><pre>enum PostType {<br>    case header(HeaderCellData)<br>    case thumbnail(ThumbnailCellData)<br>    case content(ContentCellData)<br>    case footer(FooterCellData)<br>}</pre><p>For time being, just the Cell Data as type, we will discuss it further in the article and our <em>cellForRowAtIndex(_:)</em> will look something like this —</p><pre>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        guard let data = viewModel.getPostDataAt(indexPath.row) else { return UITableViewCell() }<br>        switch data {<br>        case .header(let cellData):<br>            let cell = tableView.dequeueReusableCell(withIdentifier: &quot;HeaderCell&quot;) as! HeaderCell<br>            cell.intialize(cellData)<br>            return cell<br>        case .thumbnail(let cellData):<br>            let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ImageThumbnailCell&quot;) as! ImageThumbnailCell<br>            cell.intialize(cellData)<br>            cell.handlerUpdateView = {<br>                self.tableView.reloadRows(at: [indexPath], with: .none)<br>            }<br>            return cell<br>        case .content(let cellData):<br>            let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ContentCell&quot;) as! ContentCell<br>            cell.intialize(cellData)<br>            return cell<br>        case .footer(let cellData):<br>            let cell = tableView.dequeueReusableCell(withIdentifier: &quot;FooterCell&quot;) as! FooterCell<br>            cell.initialize(cellData)<br>            return cell<br>        }<br>    }</pre><p>So, this will remove the <em>hard if-check</em> on <em>IndexPath</em> and in-near future if we get any new different cell type then you can extend the enum’s case. You can also decide the order in which cell is going to render. It’s a WIN WIN for you✌️</p><h4>Demonstration</h4><p>Let’s create a <em>demo project</em> where we‘ll call a GET Mock API and render the above UI in UITableView. <br>PS — I would request you go through the <a href="https://github.com/greenSyntax/dynamic-uitableview-cell">sample project</a> which is attached. It will help you, as I won’t describe the basics here.</p><p>Since, we have a <strong>GET Mock API</strong> which will help us in rendering the UI — <br><a href="https://mocki.io/v1/24bef64c-6e27-460f-810e-8f2eaedaa5f2">https://mocki.io/v1/24bef64c-6e27-460f-810e-8f2eaedaa5f2</a> .</p><pre>{<br>    &quot;header&quot;: {<br>        &quot;title&quot;: &quot;Shashi Tharoor at Idea Exchange: ‘For Congress to regain its national image, it would have to make the point to Opposition parties’&quot;,<br>        &quot;description&quot;: &quot;Thiruvananthapuram MP Shashi Tharoor’s standing as a leader within and outside the Congress rose substantially after he managed to punch above his weight in the party’s presidential election in October against Mallikarjun Kharge, who had the support of the powerful All India Congress Committee (AICC) establishment.&quot;,<br>        &quot;author&quot;: &quot;Express News Service&quot;,<br>        &quot;timestamp&quot;: &quot;April 3, 2023 09:20 IST&quot;<br>    },<br>    &quot;thumbnail&quot;: {<br>        &quot;imagePath&quot;: &quot;https://images.indianexpress.com/2023/04/MP-Shashi-Tharoor.jpg?w=640&quot;<br>    },<br>    &quot;content&quot;: [<br>        &quot;In this Idea Exchange, Congress MP Shashi Tharoor speaks on why the BJP might have overreached in the Rahul Gandhi political row, the opportunity it has created for an united resistance from the Opposition and the road ahead for the Congress.&quot;,<br>        &quot;There are a couple of unintended consequences that the BJP has found itself dealing with, which, frankly, they may not have entirely expected. One is the fact that there’s been a tremendous reaction from the Opposition, where several parties — particularly regional parties who have traditionally seen the Congress as their rival in their states — have unanimously come forward and supported the Congress and Rahul Gandhi in this particular episode. One of them, the Chief Minister of Kerala, Pinarayi Vijayan, was a genuine surprise. &quot;,<br>        &quot;His party said we’re not supporting the Congress, but we’re defending democracy, which is fine because that is exactly the way that many in the Congress would like the Opposition parties to see this issue. It’s about defending our democracy and the Opposition parties’ right to have a level playing field and preventing the misuse of autonomous institutions, including the judiciary, in this case, to settle political scores.&quot;<br>    ],<br>    &quot;footer&quot;: {<br>        &quot;published&quot;: &quot;Indian Express&quot;,<br>        &quot;link&quot;: &quot;https://indianexpress.com/article/idea-exchange/shashi-tharoor-at-idea-exchange-for-congress-to-regain-its-national-image-it-would-have-to-make-the-point-to-opposition-parties-8534289/&quot;<br>    }<br>}</pre><p>And, when we convert this JSON into <em>Codable</em> Class —</p><pre><br>struct PostModel: Codable {<br>    let header: Header<br>    let thumbnail: Thumbnail<br>    let content: [String]<br>    let footer: Footer<br>}<br><br>struct Footer: Codable {<br>    let published: String<br>    let link: String<br>}<br><br>struct Header: Codable {<br>    let title, description, author, timestamp: String<br>}<br><br>struct Thumbnail: Codable {<br>    let imagePath: String<br>}</pre><p>So, I am assuming you know how to do the HTTP API Request or, you can check the source code. On Successful API Call, you will get the <em>Codable</em> Model, for me its <em>PostModel</em> —</p><pre>private var dataSource: [PostType]?<br><br>private func prepareDataSource(_ model: PostModel) {<br>        self.dataSource?.removeAll()<br>        self.dataSource = []<br>        <br>        // Header Data<br>        self.dataSource?.append(PostType.header(HeaderCellData(title: model.header.title, descrption: model.header.description, author: model.header.author, timestamp: model.header.timestamp)))<br>        <br>        // Thumbnail<br>        self.dataSource?.append(PostType.thumbnail(ThumbnailCellData(thumbnailImage: model.thumbnail.imagePath)))<br>        <br>        // Content Text<br>        let contentData = model.content.map { contentText in<br>            return ContentCellData(contentText: contentText)<br>        }<br>        <br>        contentData.forEach { cellData in<br>            self.dataSource?.append(PostType.content(cellData))<br>        }<br>        <br>        // Footer<br>        self.dataSource?.append(PostType.footer(FooterCellData(link: model.footer.link)))<br>        <br>    }</pre><p><strong>Note</strong> — In whatever order we will append, in the same order it will render the Custom Cell.<br>As I have told you earlier, <em>each enum case has an associated type</em> which is here are CellData (this will contain all those property which we need to create the <em>UITableViewCell</em>) —</p><pre>struct HeaderCellData {<br>    var title: String<br>    var descrption: String<br>    var author: String<br>    var timestamp: String<br>}<br><br>struct ThumbnailCellData {<br>    var thumbnailImage: String<br>}<br><br>struct ContentCellData {<br>    var contentText: String<br>}<br><br>struct FooterCellData {<br>    var link: String<br>}</pre><p>Until now, we have prepare Data Source which is an array of enum and those enum has associated value along with it.</p><p>Let’s move to<em> cellForRowAtIndexPath(_:) </em>—</p><pre>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        guard let data = viewModel.getPostDataAt(indexPath.row) else { return UITableViewCell() }<br>        switch data {<br>        case .header(let cellData):<br>            let cell = tableView.dequeueReusableCell(withIdentifier: &quot;HeaderCell&quot;) as! HeaderCell<br>            cell.intialize(cellData)<br>            return cell<br>        case .thumbnail(let cellData):<br>            let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ImageThumbnailCell&quot;) as! ImageThumbnailCell<br>            cell.intialize(cellData)<br>            cell.handlerUpdateView = {<br>                self.tableView.reloadRows(at: [indexPath], with: .none)<br>            }<br>            return cell<br>        case .content(let cellData):<br>            let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ContentCell&quot;) as! ContentCell<br>            cell.intialize(cellData)<br>            return cell<br>        case .footer(let cellData):<br>            let cell = tableView.dequeueReusableCell(withIdentifier: &quot;FooterCell&quot;) as! FooterCell<br>            cell.initialize(cellData)<br>            return cell<br>        }<br>    }</pre><p>Yes, <em>getPostDataAt</em> method will return the return enum at particular Index Row.</p><pre>func getPostDataAt(_ index: Int) -&gt; PostType? {<br>        return self.dataSource?[index]<br>}</pre><h4>Source Code</h4><p>🌎 Github: <a href="https://github.com/greenSyntax/dynamic-uitableview-cell">https://github.com/greenSyntax/dynamic-uitableview-cell</a></p><h4>Conclusion</h4><p>Whenever you are writing <em>cellForRowAtIndex(:_) </em>and there is some IndexPath check then, you know — you must be doing something wrong &amp; you can improve the code with enum or inheritance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c779b8357e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Network Layer in iOS (1/4)]]></title>
            <link>https://medium.com/@greenSyntax/network-layer-in-ios-1-4-bf15ba91347e?source=rss-edc7d1e2341------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf15ba91347e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[alamofire]]></category>
            <category><![CDATA[urlsessions]]></category>
            <category><![CDATA[network-design]]></category>
            <dc:creator><![CDATA[Abhishek Ravi ]]></dc:creator>
            <pubDate>Sat, 01 Apr 2023 15:28:34 GMT</pubDate>
            <atom:updated>2026-06-12T19:58:53.417Z</atom:updated>
            <content:encoded><![CDATA[<h3>Network Layer in iOS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpVRz3_RrS2JRob048B45A.png" /></figure><h4>Objective</h4><p>Network Layer is one of the most common reusable component of mobile app. Some of the question, we always keep in mind, while writing the network layer is — It should be loosely coupled with the response type &amp; network library should not be exposed to outside of the class, so that we’re not dependent on the network library.</p><h4>Agenda</h4><p>So, this series is going to be in four different parts, I don’t want to bundle each and everything under a single article —</p><h4>Part 1 — REST APIs Task</h4><ol><li>URLSession</li><li>We will write a GET and POST method and consume APIs (considering Protocol Oriented Programming)</li><li>Refactor the method and make it type loosely coupled using Generics ✌️</li><li>Re-Write the complete class with Alamofire</li></ol><h4>Part 2— Download and Upload</h4><ol><li>Download Task</li><li>Upload Task</li><li>Refactor above methods to make it more reusable and under POP</li><li>Re-write same task in Alamofire</li></ol><h4>Part 3— Alamofire Features</h4><ol><li>Reachability</li><li>Retry Mechanism on Failure</li><li>Use Middleware and Interceptor</li><li>Log Response and Metric in Firebase Performance</li><li>Handle Error Code efficiently</li></ol><h4>Part 4— UnitTest and Framework</h4><ol><li>Write Test Case of this module</li><li>Convert it into reusable module</li><li>Publish it in Cocopods</li></ol><h4>URLSession</h4><p>URLSession is part of Foundation framework which is used to do network request. It supports majorly three types of tasks —</p><ol><li><strong>Data Task</strong> — GET, POST, PUT, DELETE requests</li><li><strong>Download Task</strong>— Download resource from internet</li><li><strong>Upload Task </strong>— Upload a resource to internet</li></ol><p>Before writing code for these task, you always bother about two more thing. One is <em>URLSession</em> object and other is <em>URLSessionConfiguration</em><strong>.</strong></p><p><em>URLSessionConfiguration</em> is a dependency for <em>URLSession</em>, first you will initialise the <em>URLSessionConfiguration</em> Object and then inject it in <em>URLSession</em>. And, when you are ready with <em>URLSession</em> Object then, you can execute any of the task — data task, download task or upload task.</p><pre>import Foundation<br><br>final class URLSessionApiClient {<br>    <br>    private let configuration: URLSessionConfiguration<br>    <br>    init() {<br>        self.configuration = URLSessionConfiguration.default<br>    }<br>    <br>}</pre><p>From here, you are good to go and write the session code. But, we will explore little bit URLSessionConfiguration’s property and different types —</p><ol><li>URLSessionConfiguration.default — just default one</li><li>URLSessionConfiguration.ephemeral — uses no persistence storage</li><li>URLSessionConfiguration.background(withIdentifier: “app.example.name”) — enables background support</li></ol><p>And, every configuration has some setter property —</p><pre>self.configuration = URLSessionConfiguration.default<br>self.configuration.timeoutIntervalForRequest = 30.0<br>self.configuration.httpAdditionalHeaders = [&quot;Content-Type&quot;: &quot;application/json&quot;]</pre><p>You can go through the <a href="https://developer.apple.com/documentation/foundation/urlsessionconfiguration">documentation</a>, if you want to explore more. I just want you to know, if you want to change any behaviour in your HTTP request, always check configuration object.</p><p>Now, when you have the URLSessionConfiguration object, then you are ready to create URLSession object (since, URLSessionConfiguration is a dependency for URLSession).</p><pre>final class URLSessionApiClient {<br>    <br>    private let configuration: URLSessionConfiguration<br>    private let session: URLSession<br>    <br>    init() {<br>        self.configuration = URLSessionConfiguration.default<br>        self.configuration.timeoutIntervalForRequest = 30.0<br>        self.configuration.httpAdditionalHeaders = [&quot;Content-Type&quot;: &quot;application/json&quot;]<br>        <br>        // Create URLSession<br>        self.session = URLSession(configuration: self.configuration)<br>    }<br>}</pre><p>Since, we have <em>URLSessionConfiguration</em> object, we can create our own session object.</p><p>And, if you feel like it’s a too much of work then URLSession has given you a default session — <strong>URLSession.shared</strong></p><h4>DataTask with GET</h4><p>This task represents HTTP request which you will need to consume any REST APIs. It’s an asynchronous method, which will return <em>Data</em>, <em>URLResponse</em> and <em>Error</em> object. Let’s write a dataTask method which will look something like this —</p><pre>final class URLSessionApiClient {<br>    <br>    private let configuration: URLSessionConfiguration<br>    private let session: URLSession<br>    <br>    init() {<br>        self.configuration = URLSessionConfiguration.default<br>        self.configuration.timeoutIntervalForRequest = 30.0<br>        self.configuration.httpAdditionalHeaders = [&quot;Content-Type&quot;: &quot;application/json&quot;]<br>        <br>        self.session = URLSession(configuration: self.configuration)<br>    }<br>    <br>    func dataTask(_ url: URL) {<br>        let urlRequest = URLRequest(url: url)<br>        self.session.dataTask(with: urlRequest) { data, response, error in<br>            //TODO: Datatask Callback<br>            print(&quot;HTTP Data:\(data)&quot;)<br>        }.resume()<br>    }<br>    <br>}</pre><p>Here, dataTask(_:) always expects <em>URLRequest</em> type, so we need to create one using url.</p><pre>import UIKit<br><br>class ViewController: UIViewController {<br><br>    var client = URLSessionApiClient()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        let apiURL = URL(string: &quot;https://jsonplaceholder.typicode.com/posts/1&quot;)!<br>        client.dataTask(apiURL)<br>    }<br>}</pre><p>In console, you will get the output something like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjRV8VjE5TZmkk-3T4dFlQ.png" /></figure><p>Since, it’s going to be an asynchronous method. We need to add the completion handler in the dataTask method’s signature —</p><pre>func dataTask(_ url: URL, onCompletion: @escaping (_ result: Result&lt;Data, Error&gt;) -&gt; Void) {<br>        let urlRequest = URLRequest(url: url)<br>        self.session.dataTask(with: urlRequest) { data, response, error in<br>            <br>            // onFailure<br>            if let err = error {<br>                onCompletion(.failure(err))<br>                return<br>            }<br>            <br>            // onSuccess<br>            if let data = data {<br>                onCompletion(.success(data))<br>            } else {<br>                onCompletion(.failure(AppError.noHttpBody))<br>            }<br>        }.resume()<br>    }</pre><p>Here, we have handled the failure and success case and pass it to the completion handler with <em>Result&lt;Data, Error&gt; </em>type.</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        let apiURL = URL(string: &quot;https://jsonplaceholder.typicode.com/posts/1&quot;)!<br>        client.dataTask(apiURL) { result in<br>            switch result {<br>            case .failure(let error):<br>                print(error)<br>            case .success(let data):<br>                print(&quot;Data: \(data)&quot;)<br>            }<br>        }<br>    }</pre><p>Till now, it is good and we are getting Data type in the response, let’s try to make it more beautiful by incorporating <em>Codable</em> type in the response. So, we’ll write a <em>Codable</em> class for <a href="https://jsonplaceholder.typicode.com/posts/1">https://jsonplaceholder.typicode.com/posts/1</a> API.</p><pre>{<br>&quot;userId&quot;: 1,<br>&quot;id&quot;: 1,<br>&quot;title&quot;: &quot;sunt aut facere repellat provident occaecati excepturi optio reprehenderit&quot;,<br>&quot;body&quot;: &quot;quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto&quot;<br>}</pre><p>And, <em>Codable</em> Class for this JSON will be like —</p><pre>struct PostModel: Codable {<br>    let userId: Int<br>    let id: Int<br>    let title: String<br>    let body: String<br>}</pre><p>Now, we will refactor our <em>dataTask</em> method in <em>URLSessionApiClient. Change the completionHandler(_ result: Result&lt;Data, Error&gt;) to completionHandler(_ result: Result&lt;PostModel, Error&gt;).</em></p><pre>func dataTask(_ url: URL, onCompletion: @escaping (_ result: Result&lt;PostModel, Error&gt;) -&gt; Void) {<br>        let urlRequest = URLRequest(url: url)<br>        self.session.dataTask(with: urlRequest) { data, response, error in<br>            <br>            // onFailure<br>            if let err = error {<br>                onCompletion(.failure(err))<br>                return<br>            }<br>            <br>            // onSuccess<br>            if let data = data {<br>                // Transform Data to Codable Type<br>                if let userModel = try? JSONDecoder().decode(PosrModel.self, from: data) {<br>                    onCompletion(.success(userModel))<br>                } else {<br>                    onCompletion(.failure(AppError.decodingError))<br>                }<br>            } else {<br>                onCompletion(.failure(AppError.noHttpBody))<br>            }<br>        }.resume()<br>    }</pre><p>Note: we are using <em>JSONDecoder</em> class which is used to convert Data to <em>Codable</em> Type. This can be different article for JSONDecoder and JSONEncoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UYT5AkKXAhioqyLvPbfuzw.png" /></figure><p>This is great, but in dataTask method, we have tightly coupled with the <em>PostModel </em>class. Since, we will be using this URLSessionApiClient across the app. So, we can’t make dataTask method with <em>PostModel</em>.</p><p>Let’s make it loosely coupled with any Codable Type. Yes, we are going to intrdouce Generics —</p><pre> func dataTask&lt;T: Codable&gt;(_ url: URL, onCompletion: @escaping (_ result: Result&lt;T, Error&gt;) -&gt; Void) {<br>        let urlRequest = URLRequest(url: url)<br>        self.session.dataTask(with: urlRequest) { data, response, error in<br>            <br>            // onFailure<br>            if let err = error {<br>                onCompletion(.failure(err))<br>                return<br>            }<br>            <br>            // onSuccess<br>            if let data = data {<br>                // Transform Data to Codable Type<br>                if let userModel = try? JSONDecoder().decode(T.self, from: data) {<br>                    onCompletion(.success(userModel))<br>                } else {<br>                    onCompletion(.failure(AppError.decodingError))<br>                }<br>            } else {<br>                onCompletion(.failure(AppError.noHttpBody))<br>            }<br>        }.resume()<br>    }</pre><p>And, whoever is going to consume this dataTask method, they need to mention the Codable type —</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        let apiURL = URL(string: &quot;https://jsonplaceholder.typicode.com/posts/1&quot;)!<br>        client.dataTask(apiURL) { (_ result: Result&lt;PostModel, Error&gt;) in<br>            switch result {<br>            case .failure(let error):<br>                print(error)<br>            case .success(let data):<br>                print(&quot;Data: \(data)&quot;)<br>            }<br>        }<br>    }</pre><p>Let’s verify, if our dataTask(_:) is working properly for other APIs response — <a href="https://jsonplaceholder.typicode.com/users">https://jsonplaceholder.typicode.com/users</a>/1</p><pre>{<br> &quot;id&quot;: 1,<br> &quot;name&quot;: &quot;Leanne Graham&quot;,<br> &quot;username&quot;: &quot;Bret&quot;,<br> &quot;email&quot;: &quot;Sincere@april.biz&quot;,<br> &quot;address&quot;: {<br>  &quot;street&quot;: &quot;Kulas Light&quot;,<br>  &quot;suite&quot;: &quot;Apt. 556&quot;,<br>  &quot;city&quot;: &quot;Gwenborough&quot;,<br>  &quot;zipcode&quot;: &quot;92998-3874&quot;,<br>  &quot;geo&quot;: {<br>   &quot;lat&quot;: &quot;-37.3159&quot;,<br>   &quot;lng&quot;: &quot;81.1496&quot;<br>  }<br> }<br>}</pre><p>And, it’s <em>Codable</em> Class will be like —</p><pre>struct UserModel: Codable {<br>    let id: Int<br>    let name: String<br>    let username: String<br>    let email: String<br>    let address: UserAddress<br>}<br><br>struct UserAddress: Codable {<br>    let street: String<br>    let suite: String<br>    let city: String<br>    let zipcode: String<br>}</pre><p>Let’s try to consume <strong>/users API.</strong></p><pre>class ViewController: UIViewController {<br><br>    var client = URLSessionApiClient()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        let userAPIURL = URL(string: &quot;https://jsonplaceholder.typicode.com/users/1&quot;)!<br>        client.dataTask(userAPIURL) { (_ result: Result&lt;UserModel, Error&gt;) in<br>            switch result {<br>            case .failure(let error):<br>                print(error)<br>            case .success(let data):<br>                print(&quot;Data: \(data)&quot;)<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hfach9BFpmEInV6SU0HcaA.png" /></figure><p>Yes, it is working without any change in API Client ✌️🚀</p><h4>DataTask with POST</h4><p>We will improve our dataTask() method, instead of sending just URL in param, we need to introduce other param which is necessary for any HTTP. Those parameters are —</p><ol><li>API URL</li><li>HTTP Method</li><li>Custom Headers</li><li>Query Params in URL</li><li>HTTP Body</li></ol><p>So let’s write a <em>APIRequest</em> struct for this which will have all this.</p><pre>enum HTTPMethod: String {<br>    case GET<br>    case POST<br>    case PUT<br>    case DELETE<br>}<br><br>struct APIRequest {<br>    let url: URL<br>    let method: HTTPMethod<br>    let headers: [String: String]?<br>    let queryParams: [String: Any]?<br>    let body: Data?<br>}</pre><p>Now, we need to refactor the <em>dataTask</em> method which accepts <em>APIRequest</em> instead of just URL and incorporate these property in <em>URLSession’s</em> request.</p><pre> private func prepareURL(_ api: APIRequest) -&gt; URL? {<br>        var urlComponents = URLComponents(string: api.url.absoluteString)<br>        let queryItems = api.queryParams?.map({ (key, value) in<br>            return URLQueryItem(name: key, value: String(describing: value) )<br>        })<br>        urlComponents?.queryItems = queryItems<br>        return urlComponents?.url<br>    }<br>    <br>    func dataTask&lt;T: Codable&gt;(_ api: APIRequest, onCompletion: @escaping (_ result: Result&lt;T, Error&gt;) -&gt; Void) {<br>        <br>        guard let url = prepareURL(api) else {<br>            return onCompletion(.failure(AppError.invalidURL))<br>        }<br>        <br>        var urlRequest = URLRequest(url: url)<br>        urlRequest.httpMethod = api.method.rawValue<br>        urlRequest.allHTTPHeaderFields = api.headers<br>        urlRequest.httpBody = api.body<br>        <br>        self.session.dataTask(with: urlRequest) { data, response, error in<br>            <br>            // onFailure<br>            if let err = error {<br>                onCompletion(.failure(err))<br>                return<br>            }<br>            <br>            // onSuccess<br>            if let data = data {<br>                // Transform Data to Codable Type<br>                if let userModel = try? JSONDecoder().decode(T.self, from: data) {<br>                    onCompletion(.success(userModel))<br>                } else {<br>                    onCompletion(.failure(AppError.decodingError))<br>                }<br>            } else {<br>                onCompletion(.failure(AppError.noHttpBody))<br>            }<br>        }.resume()<br>    }</pre><p>Here, I have created an extra method <em>prepareURL, </em>which will create URL with query Params. Responsibility of prepare URL is to prepare final URL by appending query params in the URL.</p><pre>URL = https://greensyntax.app<br>Query Params = [&quot;firstName&quot;: &quot;Abhishek&quot;, lastName: &quot;Ravi&quot;]<br><br>// This is what prepareURL() method is going to do with Query Params<br>Final URL = https://greensyntax.app?firstName=Abhishek&amp;lastName=Ravi</pre><p>Let’s consume GET /<strong>users</strong> APIs —</p><pre> override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        let userAPI = URL(string: &quot;https://jsonplaceholder.typicode.com/users/1&quot;)!<br>        let apiRequest = APIRequest(url: userAPI, method: .GET, headers: nil, queryParams: nil, body: nil)<br>        client.dataTask(apiRequest) { (_ result: Result&lt;UserModel, Error&gt;) in<br>            switch result {<br>            case .failure(let error):<br>                print(error)<br>            case .success(let data):<br>                print(&quot;Data: \(data)&quot;)<br>            }<br>        }<br>    }</pre><p>Now, let’s try to consumer POST /<strong>posts</strong> API where we need to pass the body and headers (let’s assume).</p><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        let newPost = PostModel(userId: 1234, id: 1234, title: &quot;My Title&quot;, body: &quot;This is Body&quot;)<br>        let newPostData = try? JSONEncoder().encode(newPost)<br>        <br>        let postsAPI = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;)!<br>        let apiRequest = APIRequest(url: postsAPI, method: .POST, headers: [&quot;Content-Type&quot;:&quot;application/json&quot;], queryParams: nil, body: newPostData)<br>        client.dataTask(apiRequest) { (_ result: Result&lt;PostModel, Error&gt;) in<br>            switch result {<br>            case .failure(let error):<br>                print(error)<br>            case .success(let data):<br>                print(&quot;Data: \(data)&quot;)<br>            }<br>        }<br>    }</pre><p>And, if everything went well, you will get status code as `201` and response body would be something like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFTMkHn4o8eHhw5DC8Hr5Q.png" /></figure><p>Last thing, I just want to make a small change in API Client. I want to introduce HTTP Status Code Validation Check.</p><pre>func dataTask&lt;T: Codable&gt;(_ api: APIRequest, onCompletion: @escaping (_ result: Result&lt;T, Error&gt;) -&gt; Void) {<br>        <br>        guard let url = prepareURL(api) else {<br>            return onCompletion(.failure(AppError.invalidURL))<br>        }<br>        <br>        var urlRequest = URLRequest(url: url)<br>        urlRequest.httpMethod = api.method.rawValue<br>        urlRequest.allHTTPHeaderFields = api.headers<br>        urlRequest.httpBody = api.body<br>        <br>        self.session.dataTask(with: urlRequest) { data, response, error in<br>            <br>            // onFailure<br>            if let err = error {<br>                onCompletion(.failure(err))<br>                return<br>            }<br>            <br>            // Validation<br>            guard (200...299).contains((response as? HTTPURLResponse)?.statusCode ?? 0) else {<br>                onCompletion(.failure(AppError.httpFailure))<br>                return<br>            }<br>            <br>            // onSuccess<br>            if let data = data {<br>                // Transform Data to Codable Type<br>                if let userModel = try? JSONDecoder().decode(T.self, from: data) {<br>                    onCompletion(.success(userModel))<br>                } else {<br>                    onCompletion(.failure(AppError.decodingError))<br>                }<br>            } else {<br>                onCompletion(.failure(AppError.noHttpBody))<br>            }<br>        }.resume()<br>    }</pre><h4>Introduce Alamofire</h4><p>Alamofire is a popular network library for iOS, you can use Alamofire instead of URLSession. You can go through Alamofire’s <a href="https://github.com/Alamofire/Alamofire">github page</a> for other features they have. Right now, we are just bothered about the HTTP Data Request and consume GET and POST APIs via Alamofire.</p><pre># Open Project<br># Create Pod file and open it<br># Add pod &#39;Almofire&#39; <br># Run pod install command</pre><p>So, I will try to just re-write the same implementation using Alamofire. Codes are self explanatory, if you get the URLSession then, Alamofire is just an abstraction over it.</p><pre>import Foundation<br>import Alamofire<br><br>final class AlamofireApiClient: NetworkClient {<br>    <br>    private let session = AF.session<br>    <br>    private func prepareURL(_ api: APIRequest) -&gt; URL? {<br>        var urlComponents = URLComponents(string: api.url.absoluteString)<br>        let queryItems = api.queryParams?.map({ (key, value) in<br>            return URLQueryItem(name: key, value: String(describing: value) )<br>        })<br>        urlComponents?.queryItems = queryItems<br>        return urlComponents?.url<br>    }<br>    <br>    func dataTask&lt;T&gt;(_ api: APIRequest, onCompletion: @escaping (Result&lt;T, Error&gt;) -&gt; Void) where T : Decodable, T : Encodable {<br>        <br>        guard let url = prepareURL(api) else {<br>            return onCompletion(.failure(AppError.invalidURL))<br>        }<br>        <br>        var urlRequest = URLRequest(url: url)<br>        urlRequest.httpMethod = api.method.rawValue<br>        urlRequest.allHTTPHeaderFields = api.headers<br>        urlRequest.httpBody = api.body<br>                <br>        AF.request(urlRequest).validate().response { response in<br>            <br>            // onFailure<br>            if let err = response.error {<br>                onCompletion(.failure(err))<br>                return<br>            }<br>            <br>            // onSuccess<br>            if let data = response.data {<br>                // Transform Data to Codable Type<br>                if let userModel = try? JSONDecoder().decode(T.self, from: data) {<br>                    onCompletion(.success(userModel))<br>                } else {<br>                    onCompletion(.failure(AppError.decodingError))<br>                }<br>            } else {<br>                onCompletion(.failure(AppError.noHttpBody))<br>            }<br>        }<br>    }<br>    <br>}</pre><p>Here, NetworkClient is a protocol for both the Clients to keep the contract remain same.</p><pre>protocol NetworkClient {<br>    func dataTask&lt;T: Codable&gt;(_ api: APIRequest,<br>                              onCompletion: @escaping (_ result: Result&lt;T, Error&gt;) -&gt; Void)<br>}</pre><p>Response for the both the GET and POST APIs which we have tested for URLSession.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6avsduHw5LwNhusDsm40Q.png" /></figure><h4>🌎 <strong>Source Code</strong></h4><p>Github: <a href="https://github.com/greenSyntax/network-layer">https://github.com/greenSyntax/network-layer</a><br><em>Branch </em><strong><em>: </em></strong><em>feature/alamofire </em>and main</p><h4>Conclusion</h4><p>Here, we gone through the process how we should design a Network Layer. Majorly, we discussed GET and POST APIs with URLSession and Alamofire. I usually prefer URLSession in my projects if I am just consuming GET and POST APIs, but if has has caching, logging, metric analysis, upload &amp; download then, I will obviously go for Alamofire as, it’s a mature library which is relevant from a long time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf15ba91347e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Sign-On in iOS]]></title>
            <link>https://medium.com/@greenSyntax/single-sign-on-on-ios-cc0af3d03aaa?source=rss-edc7d1e2341------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc0af3d03aaa</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[single-sign-on]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Abhishek Ravi ]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 14:39:09 GMT</pubDate>
            <atom:updated>2023-03-30T14:49:51.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*_mWgtmnaENc1VEWas87KkQ.png" /></figure><h4>Smalltalk</h4><p>Of late, you must have seen app community is promoting <strong><em>Single Sign On</em></strong> instead of conventional login-signup process. Yes, conventional one was a tiresome process to onboard a user and obviously no one wants to have a burden of remembering password. I believe, the onboarding conversion must be high % comparison to <em>conventional onboarding</em> process. So, if you are building an app where there is no need of mobile number, then single sign on (or, social login) is best options out there.</p><h4>Demo</h4><p>I was working on one of my pet project where I have to implement SSO with Google and Apple. If you are implementing SSO, make sure you don’t forget to put Apple Login as Apple Review Team will reject your app ✌️😁</p><p><strong>Apology</strong> : Since, it’s a pet project of mine, I can’t share the github with you. Bear this time.</p><h4>Sequence Diagram</h4><p>We have an assumption, that auth can be either initiated by Google or Apple. This is a WIP sequence diagram (not a good one, though).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxzZM0AE7HeZ5m2eqrgooA.png" /></figure><h4>Prerequisite</h4><ol><li>I am expecting, you to know — How to setup Firebase in your iOS Project. Add <strong>GoogleService-Info.plist </strong>in your project which you will get in Firebase Console’s Project Setting. (or, follow this <a href="https://firebase.google.com/docs/ios/setup?authuser=0&amp;hl=en">Firebase Integration</a>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxqJQ7jEnG1DDbttpBMM1w.png" /></figure><p>2. Enable <strong>Google</strong> And <strong>Apple</strong> Authentication in <strong>Authentication</strong> setion of Firebase Console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7qa1OWhxsczkeHZ4Ec1pQ.png" /></figure><p>3. For Google SignIn, we need to add <strong>REVERSED_CLIENT_ID</strong> in URL Scheme of your Project. You will get this value in <strong>Google Service plist</strong> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJ_RyWJD5LzCJi3quOlEjA.png" /></figure><h4>Firebase Authentication</h4><p>We will using Firebase Authentication, which will help us in achieving single sign-on authentication for different social accounts like — facebook, google, apple, twitter or gihub. There are certainly more than this social login options, we will stuck on Google and Apple Authentication.</p><p>So, your <strong>Pod</strong> file should look like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErZZAJc6GWtaxwco-l_opQ.png" /></figure><p>and, run <strong>pod install.</strong></p><h4>Implementation</h4><p>Till now, you have <strong>Firebase Authentication</strong> module in your project, and you’re ready to implement your Authentication layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*K33eeLzluQwXi4s9GJwrAQ.png" /></figure><p>Here, I will be implementing Google and Apple for my app. You can go through Firebase Documentation for other SSO integration.</p><p>Like any Old School Developer, here I will be using Delegate Pattern for Communication in Google and Apple Auth Layer.</p><pre>struct AppUser {<br>    var token: String<br>    var name: String<br>    var email: String<br>    var userId: String<br>    var imagePath: URL?<br>}<br><br>protocol SocialAuthenticationDelegate: AnyObject {<br>    func onAuthenticationSuccess(_ user: AppUser)<br>    func onAuthenticationError(_ error: Error)<br>}</pre><h4>Google Authentication</h4><p>In Google Authentication, we will need Firebase <strong>ClientID </strong>which we will get from Google Service plist file.</p><pre><br>import Foundation<br>import GoogleSignIn<br>import FirebaseAuth<br>import Firebase<br><br>class GoogleAuthentication {<br>    <br>    weak var delegate: SocialAuthenticationDelegate?<br>    <br>    func signIn(_ vc: UIViewController, delegate: SocialAuthenticationDelegate) {<br>        guard let clientID = FirebaseApp.app()?.options.clientID else { return }<br>        self.delegate = delegate<br>        <br>        let config = GIDConfiguration(clientID: clientID)<br>        GIDSignIn.sharedInstance.configuration = config<br>        GIDSignIn.sharedInstance.signIn(withPresenting: vc) { [unowned self] user, error in<br>            <br>            if let error = error {<br>                self.delegate?.onAuthenticationError(AppError.custom(error.localizedDescription))<br>                return<br>            }<br>            <br>            guard let token = user?.user.accessToken, let idToken = user?.user.idToken else { return }<br>            let credential = GoogleAuthProvider.credential(withIDToken: idToken.tokenString, accessToken: token.tokenString)<br>            Auth.auth().signIn(with: credential) { (auth, error) in<br>                if let error = error {<br>                    debugPrint(&quot;Auth Error: \(error.localizedDescription)&quot;)<br>                    self.delegate?.onAuthenticationError(AppError.custom(error.localizedDescription))<br>                } else {<br>                    self.delegate?.onAuthenticationSuccess(AppUser(token: auth?.user.providerID ?? &quot;&quot;, name: auth?.user.displayName ?? &quot;&quot;, email: auth?.user.email ?? &quot;&quot;, userId: auth?.user.uid ?? &quot;&quot;, imagePath: auth?.user.photoURL))<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>And, to consume this class which is pretty simple. From the sequence diagram, you can sense that I will be calling GoogleAuthentication from ViewModel.<br>So, ViewModel will privately hold the reference of any SSO Layer.</p><pre>class AuthenticationViewModel: AuthenticationViewModelType {<br>    <br>    private var google: GoogleAuthentication<br>    <br>    var handlerAuthenticationSuccessfull: ((_ user: AppUser) -&gt; Void)?<br>    var handlerAuthenticationFailure: ((_ error: AppError) -&gt; Void)?<br>    <br>    init(_ google: GoogleAuthentication) {<br>        self.google = google<br>    }<br>    <br>    func initializeGoogleLogin(_ vc: UIViewController) {<br>        google.signIn(vc, delegate: self)<br>    }<br>    <br>}<br><br>extension AuthenticationViewModel: SocialAuthenticationDelegate {<br>    func onAuthenticationSuccess(_ user: AppUser) {<br>        self.handlerAuthenticationSuccessfull?(user)<br>    }<br>    <br>    func onAuthenticationError(_ error: Error) {<br>        self.handlerAuthenticationFailure?(.error(error))<br>    }<br>}</pre><p><strong>SocialAuthenticationDelegate </strong>is a delegate which will respond to ViewModel, when there is some Success or Failure callback.</p><p>In ViewController Layer, you will just call the method —</p><pre>@IBAction func actionButtonGoogle(_ sender: Any) {<br>     viewModel.initializeGoogleLogin(self)<br>}</pre><p>If I have conclude, then it will be more like — <br>ViewController → ViewModel → GoogleAuthentication, after the completion, GoogleAuthentication will respond to its Delegate which is ViewModel abut the Success or Failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKMuUg7bt_EM_MBSypzzcQ.png" /></figure><h4>Apple Authentication</h4><p>Just like google authentication, Apple Auth is the same except lots of boiler plat codes which I copied from Firebase Documentation. I may write next part of Apple Authentication. For now, consider its boilerplate code.</p><pre>class AppleAuthentication: NSObject {<br>    <br>    fileprivate var currentNonce: String?<br>    <br>    weak var delegate: SocialAuthenticationDelegate?<br>    <br>    func startSignInWithAppleFlow() {<br>        let nonce = randomNonceString()<br>        currentNonce = nonce<br>        let appleIDProvider = ASAuthorizationAppleIDProvider()<br>        let request = appleIDProvider.createRequest()<br>        request.requestedScopes = [.fullName, .email]<br>        request.nonce = sha256(nonce)<br>        let authorizationController = ASAuthorizationController(authorizationRequests: [request])<br>        authorizationController.delegate = self<br>        authorizationController.performRequests()<br>    }<br>    <br>}<br><br>extension AppleAuthentication: ASAuthorizationControllerDelegate {<br>    <br>    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {<br>        print(&quot;Sign in with Apple errored: \(error)&quot;)<br>        delegate?.onAuthenticationError(AppError.custom(error.localizedDescription))<br>    }<br>    <br>    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {<br>        <br>        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {<br>            guard let nonce = currentNonce else {<br>                delegate?.onAuthenticationError(AppError.custom(&quot;A login callback was received, but no login request was sent.&quot;))<br>                return<br>            }<br>            guard let appleIDToken = appleIDCredential.identityToken else {<br>                delegate?.onAuthenticationError(AppError.custom(&quot;Unable to fetch identity token&quot;))<br>                return<br>            }<br>            guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {<br>                debugPrint(&quot;Unable to serialize token string from data: \(appleIDToken.debugDescription)&quot;)<br>                delegate?.onAuthenticationError(AppError.custom(&quot;Unable to serialize token string from data&quot;))<br>                return<br>            }<br>            // Initialize a Firebase credential.<br>            let credential = OAuthProvider.credential(withProviderID: &quot;apple.com&quot;,<br>                                                      idToken: idTokenString,<br>                                                      rawNonce: nonce)<br>            // Sign in with Firebase.<br>            Auth.auth().signIn(with: credential) { (authResult, error) in<br>                if let err = error {<br>                    self.delegate?.onAuthenticationError(AppError.custom(err.localizedDescription))<br>                    return<br>                }<br>                // User is signed in to Firebase with Apple.<br>                if let user = authResult?.user {<br>                    self.delegate?.onAuthenticationSuccess(AppUser(token: &quot;&quot;, name: user.displayName ?? &quot;&quot;, email: user.email ?? &quot;&quot;, userId: user.uid, imagePath: user.photoURL))<br>                }<br>            }<br>        }<br>    }<br>}<br><br>extension AppleAuthentication {<br>    <br>    private func sha256(_ input: String) -&gt; String {<br>        let inputData = Data(input.utf8)<br>        let hashedData = SHA256.hash(data: inputData)<br>        let hashString = hashedData.compactMap {<br>            return String(format: &quot;%02x&quot;, $0)<br>        }.joined()<br>        <br>        return hashString<br>    }<br>    <br>    private func randomNonceString(length: Int = 32) -&gt; String {<br>        precondition(length &gt; 0)<br>        let charset: Array&lt;Character&gt; =<br>        Array(&quot;0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._&quot;)<br>        var result = &quot;&quot;<br>        var remainingLength = length<br>        <br>        while remainingLength &gt; 0 {<br>            let randoms: [UInt8] = (0 ..&lt; 16).map { _ in<br>                var random: UInt8 = 0<br>                let errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &amp;random)<br>                if errorCode != errSecSuccess {<br>                    fatalError(&quot;Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)&quot;)<br>                }<br>                return random<br>            }<br>            <br>            randoms.forEach { random in<br>                if remainingLength == 0 {<br>                    return<br>                }<br>                <br>                if random &lt; charset.count {<br>                    result.append(charset[Int(random)])<br>                    remainingLength -= 1<br>                }<br>            }<br>        }<br>        <br>        return result<br>    }<br>}</pre><p>After the Apple Authentication introduction, I need to do some modification in ViewModel layer —</p><pre><br>class AuthenticationViewModel: AuthenticationViewModelType {<br>    <br>    private var apple: AppleAuthentication<br>    private var google: GoogleAuthentication<br>    <br>    var handlerAuthenticationSuccessfull: ((_ user: AppUser) -&gt; Void)?<br>    var handlerAuthenticationFailure: ((_ error: AppError) -&gt; Void)?<br>    <br>    init(_ apple: AppleAuthentication, _ google: GoogleAuthentication) {<br>        self.apple = apple<br>        self.google = google<br>    }<br>    <br>    func initiateAppleLogin() {<br>        apple.delegate = self<br>        apple.startSignInWithAppleFlow()<br>    }<br>    <br>    func initializeGoogleLogin(_ vc: UIViewController) {<br>        google.signIn(vc, delegate: self)<br>    }<br>    <br>}<br><br>extension AuthenticationViewModel: SocialAuthenticationDelegate {<br>    func onAuthenticationSuccess(_ user: AppUser) {<br>        self.authenticateUser(user)<br>    }<br>    <br>    func onAuthenticationError(_ error: Error) {<br>        self.handlerAuthenticationFailure?(.error(error))<br>    }<br>}</pre><p>And, all this will be called from ViewController —</p><pre>  <br>    @IBAction func actionButtonGoogle(_ sender: Any) {<br>        viewModel.initializeGoogleLogin(self)<br>    }<br>    <br>    @IBAction func actionButtonApple(_ sender: Any) {<br>        viewModel.initiateAppleLogin()<br>    }</pre><h4>Troubleshoot</h4><ol><li>Firebase not configured successfully, make sure you initialise the Firebase before the Google Authentication Initialisation. Best way is to initialise the Firebase in AppDelegate’s didFinish Launching method.</li><li>Verify your Scheme User of app. It should be Reversed Client ID.</li><li>In Firebase Console, check Google SignIn is enabled in Firebase Authentication (same for Apple Authentication).</li></ol><h4>Reference</h4><p><a href="https://firebase.google.com/docs/auth?authuser=0&amp;hl=en">Firebase Documentation</a><br><a href="https://developer.apple.com/documentation/authenticationservices/implementing_user_authentication_with_sign_in_with_apple">Apple Login</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc0af3d03aaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Think in SOLID]]></title>
            <link>https://medium.com/@greenSyntax/think-in-solid-7bb3977bb0c5?source=rss-edc7d1e2341------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb3977bb0c5</guid>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[solid-principles-in-swift]]></category>
            <dc:creator><![CDATA[Abhishek Ravi ]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 22:12:02 GMT</pubDate>
            <atom:updated>2023-01-08T22:39:14.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*670B1TolwhyhnvB8YLUONQ.png" /></figure><h4>Objective</h4><p>How this article is going to be different from other articles on SOLID Principle which are already on internet. So, I always had problem with the relatability factor while reading those articles which were written in difference perspective or different language. Here, I will go through the thought process while writing some daily swift code and how I apply SOLID to it.</p><p>Here, I am not going to bring anything different on the table which is already not on medium, but this article is for all iOS Developer (or, mobile developer) which are struggling to think in SOLID. <br>This is going to be a bit lengthy article, as I am taking you through a <strong>write-code-and-then-fix-it-with-solid </strong>template.</p><h4>Anatomy of SOLID</h4><ol><li><strong>S</strong>ingle Responsibility Principle</li><li><strong>O</strong>pen-Closed Principle</li><li><strong>L</strong>iskov Substitution Principle</li><li><strong>I</strong>nterface Segregation Principle</li><li><strong>D</strong>ependency Inversion Principle</li></ol><h3><strong>Single Responsibility Principal</strong></h3><blockquote><strong>✏️ def: Every class should have only single responsibility.</strong></blockquote><p>This is very fundamental principal for any developer to understand. Each time while writing your code, always ask yourself if this piece of code can be a reusable code or can we outsource this piece of code to a separate class which will own individual responsibility, if yes then turn that piece of code into a class. And make sure, each class should have an objective and it’s purpose defined. There is nothing wrong in creating too many class files 🙋🏻‍♂️ just to follow this principal. <br>Sometimes, you will ask yourself — why I am creating this class just for a single method. Trust me, it’s a good habit and approach towards an extensible coding practice.</p><p><strong>Situation</strong> : You were given to write a <strong>Network Client Layer</strong> (or, APIManager) for your app whose objective is to call Network APIs and parse the JSON response and then send it to the consumer (or, view controller).</p><p><strong>Approach</strong> : You will create a Network Client class first, and then expose a public method which will call the API. For now, it will accept a /get URL (for the time being) and completion handler with a response model’s object in it. I have kept ResponseModel as optional type just to make it suited to handle error case. <br> — on Success, your response model will be populated with response data.<br> — onFailure, your response model will be nil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SC-Ru1jLjplPfCbk0NzbOQ.png" /></figure><p>Here, ResponseModel is class which will map the JSON to Swift Type (or, you can serialised model class). Objective of this method is to accept a URL from consumer and get a completion handler (or, async closure) which will either have response model or not.</p><p>Now, I want to refactor this completion handler signature as, I can’t pass Error object on failure case. My ViewController can’t tell why API got failed. As of now, they will just get a nil object which is a poor way of telling error occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrWfeVBJcMSZUdS9BvUyvQ.png" /></figure><p>Here, I have introduced <strong>Result Type </strong>just to have Response Model and Error type in Completion handler. Now, I can pass model object or error in success/failure cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0dsDKWBOwSusu1dkugUXQ.png" /></figure><p>From here, we are going to write URLSession code for GET HTTP Request and then, Parse the JSON into a Response Model Type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQ0zhKZbvket_64e-GWl5w.png" /></figure><p>Here, I have just create a HTTP get Request and parsed the JSON to ResponseModel.</p><p>Here comes the small violation of Single Responsibility Principal. So, we have written the Http Request code and JSON Parsing in the same class. To make it more reusable, we can outsource the JSON Parsing responsibility to a separate class.</p><p>Let’s remove the JSON Decoder part to a separate JSON Parser class —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqOF4z9YZ_Estw1AW7hLpQ.png" /></figure><p>Now, we will use this class in Network Class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlBHoBJVZ97jWN6VAt81Lg.png" /></figure><p>Here, Network Layer has the responsibility of HTTP Network Calls and JSON Parser class has the responsibility of JSON Decoding.</p><p>If I ask you what is the advantage of doing this — <br>Say, in near future you get some new library which will parse JSON Data to Model Object then you just need to update the JSON Parser class, NetworkLayer will have no change since, Parsing Logic is getting changed. Same for the Network Layer, if we are updating URLSession to Alamofire (very popular iOS Network Library) then you will only bother about HTTP network implementation, JSON Parser Code will remain same.</p><p>There is something which I need to refactor in JSON Parser, as we have hard code the ResponseModel type, let’s make it generic so that it can support all the Decodable Type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spi8Zhqt94Qy18I6s-TXmQ.png" /></figure><p><strong>✅ Conclusion</strong> : Each Class should have single responsibility, if there is more than one, then split it into more classes, even if the class has just single method in it.</p><h3>Open Close Principal</h3><blockquote><strong>✏️ def: A class is open for extension and closed for modification.</strong></blockquote><p>This seems simple, but how an extension and modification word are different from each other. How will I identify, my class is extensible.</p><p>So, we will address this with a regular problem statement. Say, you are creating an eCommerce app which has a payment screen which has multiple Payment Modes like Google Pay, PhonePe UPI and Paypal.</p><p>Here, I am assuming every payment request need a OrderId and transactionId to initiate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9R-B5TjB1w0KNtzBpm8HAA.png" /></figure><p>Now, you got to know that we need to add an another Payment Mode i.e. Stripe Payment Mode for International Payment System. Then, you need to add extra case for ‘stripe’ in your method block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0r6Y0xEeieLXbOxPotxXYQ.png" /></figure><p>So, this is a classic case of Modification of Class. Extension will be when you don’t have to change any line of code.</p><p>Next, we are going to re-write the same code and made it extensible and smart 🏆</p><p>First, we are going to introduce separate class for all the Payment SDK Mode — GooglePaySDK, PhonePeSDK, Paypal SDK and each class will have their separate implementation of their payment.</p><p>Yes, we are celebrating Separation of Concern 🎮</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsNUID9pCvIUAqyIb7bCBQ.png" /></figure><p>Here, I have created for GooglePay and aded the pay method signature.</p><p>If You go to PhonePeSDK or PaypalSDK — all of them have the same pay method signature. Whenever such things come to you, always create a Protocol for that and make it mandatory for concrete class to adopt it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cwiHqb9OHqozF6kkoEhRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3LOiWD2gGv5MZEIquQcOg.png" /></figure><p>And, PaymentModeProtocol is the result of that observation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xm8D0VhGoQyjaNZ0uqTr4Q.png" /></figure><p>Here I come, I create a protocol named PaymentModeProtocol which will be adopted by all the Payment Methods like GooglePay, PhonePe and Paypal which will enforce them to adopt the pay method with same signature.</p><p>After all the effort, its time to refactor your Payment Gateway Class which has switch method.</p><p>Before Refactoring —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksF_KMoBSt-TZ7UinMxqmQ.png" /></figure><p>After Refactoring —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufHGmV7yni9KCxXVYq9_uQ.png" /></figure><p>Ah, just one line of code for big switch block.</p><p>Here, I have made the PaymentMethod to PaymentMethodProtocol, since all the concrete payment mode class which I will pass in it, will obviously belongs to PaymentMethodProtocol.</p><p>Next, I have removed the switch case, as I will rely on on Concrete Objects (i.e. GooglePaySDK or PhonePeSDK or PaypalSDK) and depending on that it will call pay method of that object.</p><p>Now, this is an Extensible class. If you add any new class like StripeSDK class and adopt it with PaymentModeProtocol, you are good to go with your existing flow without adding any extra code. Yeah, PaymentGateway is closed for modification, and always open for extension⚡️</p><h3>Liskov Substitution Principle</h3><blockquote><strong>✏️ def: child type must be substitute-able by their parent type.</strong></blockquote><p>Assume, you are writing an eCommerce app, where you will have different products type. As thumb rules says, we need to identify the common attributes which is going to be in all the Products Type.</p><p>Here, I will write a protocol of Product Type with common attributes. And, I have written an Electronic Product type which is adopting the Product Protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HflNHCAmQ3kSNO6gDoxpWQ.png" /></figure><p>So, whenever I need to show to Payable Price to user then, I will call getPayablePrice() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ppVjjVHgaDImmDIIShjFgA.png" /></figure><p>Now, there is an another use-case where Clothing Product will going to have a Discounted Price along with the Discount Value.</p><p>So, we will write an another class for ClothingProduct —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2F5-OpTFSRlf2Z08_COPJA.png" /></figure><p>As, you can see there is another method which will return the Discounted Price — <strong>getDiscountPayablePrice()</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1N6M_g2EYUzERKg4a9A-nQ.png" /></figure><p>Now, we will test our class whether they are following Liskov Substitution Principle. As Liskov Substitution says, Child Objects must be replaceable with their parent type. Now, I will add <strong>Product</strong> type to their references,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZgDc7UpfOpxaG3SaljiAg.png" /></figure><p>As, you can see getDiscountPayablePrice() method is throwing error as it doesn’t belong to the protocol. So, we need to fix this —</p><p>First of all, we will remove the getDiscountedPayablePrice() method as it’s not there is protocol, so we’ll try to keep only those methods which are mentioned in Product protocol.<br>And, we’ll fix the price calculation logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvG3Ctt1u_rd84AI3cMehw.png" /></figure><p>As you can see, child classes references are respecting the parent type. Yes, this is following Liskov Substitution Principle.</p><h3>Interface Segregation Principle</h3><blockquote><strong>✏️ def: a class should depend on possible interface rather than a big fat interface.</strong></blockquote><p>This principle suggest you to create multiple small interface instead a big fat interface which will have all the required method/ property.</p><p>For this, I have a very common example which suits this use case —</p><p>You always create a <strong>BaseViewController</strong> class in your project which is inherited by all the UIViewController class. So that, duplicate code can be minimised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zeCwzLpoND-gOTXRUq_gqA.png" /></figure><p>And, your ViewController will inherit with BaseViewController which will expose all the methods to child ViewController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBZKYF-cEVELtOlRquPb5A.png" /></figure><p>Now, this is some old school coding practice, now usually dev write a UIViewController extension or Protocol + Protocol Extension to achieve that. I’ll re-write this same BaseViewController in Protocol+Protocol Extension pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fH-X4dnIG_7xxDD4mKRW1g.png" /></figure><p>And, you will tell all your UIViewController to adopt this BaseViewControllerProtocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZUra0w-7eYiFhfxUlLAEQ.png" /></figure><p>Yeah, same code , different pattern.</p><p>Here, <strong>BaseViewControllerProtocol</strong> is the Fat Interface what Interface Segregation principle is warning us about.</p><p>Principle suggest us to create small interfaces (or, protocol) instead of one big fat interface. Let’s split the fat interface into small interfaces depending upon their objectivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CywlT_qhMrqSPV86P--G2g.png" /></figure><p>For time being, just ignore the Protocol Naming Convention if its triggering you. Here, I have created three separate protocol.</p><p>Now you will ask me, why there is need of creating small interfaces ? Seems like an extra work, Right ?</p><p>What if, there is ViewController where there is no need of ErrorView or Loadable then, in fat interface you can’t segregate the capability for your ViewController. Here you can —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lheoOP8-VoaToIpEPGQWTw.png" /></figure><h3>Dependency Inversion</h3><blockquote><strong>✏️ def: If two modules of code are communicating with each other, if one module is injecting the dependency to other then it should always be interface or protocol type instead of concrete type.</strong></blockquote><p>Imagine you are writing a eCommerce App. There is a list of products and when you tap on one of them then you navigate to a detail screen.<br>So, we have two modules — List and Detail.</p><p>Detail Screen is always dependent on Product List Module’s item. In other words, Details Screen can’t get rendered if there is No ProductId or Product Object. Here, ProductObject or ProductId is a dependency for Detail Module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueO1es0hsIkp6yZo9iN3Ew.png" /></figure><p>Here, Dependency Module’s initialise method is configurator. Next, we will add one more fix by replacing Product Type with the Product protocol. So that, we can create it as a Loosely coupled code.</p><h3>Conclusion</h3><p>SOLID is Design Principle Theory not a pattern and you will find different design pattern based on these principles. Always try to deduced your use-case with these principle. Think in SOLID 🤘🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb3977bb0c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSL Pinning in iOS]]></title>
            <link>https://medium.com/@greenSyntax/ssl-pinning-in-ios-f508b5860ead?source=rss-edc7d1e2341------2</link>
            <guid isPermaLink="false">https://medium.com/p/f508b5860ead</guid>
            <category><![CDATA[ios-security]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ssl-pinning]]></category>
            <dc:creator><![CDATA[Abhishek Ravi ]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 21:41:09 GMT</pubDate>
            <atom:updated>2022-12-29T21:59:31.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6ED8F_ZuQoVPv6jJJtJ6w.png" /></figure><h4>What is the ‘Man in The Middle’ Attack ?</h4><p>Let’s start with some boring definition — A man-in-the-middle (MITM) is a type of cyber attack in which the attackers secretly intercepts the message between client and server. <br>So, this is the definition which you’ll get on the internet about MITM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JseiaS41ZjsrRjeLpSe8pA.png" /></figure><p>If I have to tell you in a lay-man words, then it will be like — <br>You’re having a phone conversation with your friend and you have a belief that, only your friend can listen what you’re saying i.e. One to One Conversation.<br>When some attacker comes in between you two &amp; tape your phone conversation (This is MITM, when there is a third person comes in between your one-to-one connection).</p><p>As a consumer, you always wants your tele-communication partner to tell you when your phone conversation is monitored — Yes, this is SSL Pinning for you.</p><blockquote>🙋🏻‍♂️ SSL Pinning will tell you when your connection is compromised or monitored.</blockquote><h4>How SSL Pinning Can Fix</h4><p>Before we start, let me state what is SSL — Secure Socket Layer.<br>It’s a cryptographic protocol designed to provide communication security over computer network.</p><blockquote>// TODO: I’ll talk about SSL/TLS in a separate article.</blockquote><p>So, SSL Pinning is a process of introducing SSL Certificate between the Client App and Server (or, API Gateway) so that, each connection is encrypted &amp; secure. It’s more like, a private key is kept at Server and Public key is distributed to the clients such that each conversation can encrypted by the respective key(s).</p><h4>Choose between SSL Public Key and SSL Certificate</h4><p>There are two ways of SSL Pinning in your app — <br>1. SSL Pinning via Certificate (In this article, we’ll explore this)<br>2. SSL Pinning via Public Key</p><p>AFAIK, there is only one advantage of Public Key over Certificate is Expiration of Key.<br>Public Key will never expire, where SSL Certificate has some definite time of validity.</p><h4>Demo Project</h4><p>I have created a demo project which has Alamofire &amp; URL Session’s data request to a GET API <strong>without any SSL Pinning</strong>.<br>You must have little understanding of API Request with Alamofire and URLSession.<br>Further, we’re making request with SSL Pinned in this article. <br>Before we move ahead, please clone this project from ‘<strong>feature/without-ssl-pinning</strong>’ branch.</p><pre>git clone -b feature/pre-ssl-pinning git@github.com:greenSyntax/ssl-pinning-demo.git</pre><p>Branch <strong>‘main</strong>’ will have the final code after SSL Pinning, which you can checkout later.</p><h4>Prerequisite for SSL Pinning</h4><p>You need a free API which you can use for demonstration. Here, I will be using <strong>run.mocky.io</strong> and it’s SSL Public Certificate.<br>Later, in this article I will be helping you how to get SSL Certificate.</p><p>Here, we have Mocky’s GET URL —</p><pre>https://run.mocky.io/v3/77e82362-7222-46fa-a6ab-c2203c9df461</pre><pre>{<br>&quot;id&quot;: 1,<br>&quot;userId&quot;: 123,<br>&quot;title&quot;: &quot;Hello World&quot;,<br>&quot;body&quot;: &quot;iOS SSL Pinning&quot;<br>}</pre><p>Since, we are using run.mocky.io, so we’ll need a Public SSL Certificate which is bound with this domain-name that we will use in our demo app.</p><p>Let’s open the URL in your browser and get the SSL Certificate — <br>1. Click on the ‘Lock’ icon,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ipmf5CyyE3NQq2cybXU7g.png" /></figure><p>2. Next, you will be exporting SSL Certificate which is bundled with it,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CihgW0cT3312iZXNvf5kA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oEuuaa4TtpG-rWM3mQr3vQ.png" /></figure><p>3. Export the Certificate in *.cer formate with DER encoded binary.</p><p>Just add this certificate file in your demo project and make sure, you add this in project target.</p><h4>What is Proxy Application ?</h4><p>Proxy application will show the HTTP network traffic of your phone or device. <a href="https://www.charlesproxy.com/">Charles</a> is one of the most popular option for this. <br>Here, I am considering you’ve Charles on your machine (Please bear this with me, later I will write an article on Charles Setup).</p><h4>Without SSL Pinning</h4><p>If there is No SSL Pinning in your app, then you can easily monitor the network traffic by any Proxy App like Charles.<br>You can monitor the response or request, adulterate as per your need. This will behave like MITM.</p><p>Meantime, If I run my demo app, this is a screenshot of Charles how it looks like when Charles monitor my Wifi Traffic—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-oaXgd8hekk_k9yhuR_7Q.png" /></figure><p>Here, I can see the JSON response what I am getting for my demo app. Yes, this is very threatening as an app user ‘coz, whatever data that is passed to app can be seen here on Charles. Adding to it, you can edit the response and request.</p><h4>With SSL Pinning</h4><p>And, when, you enable SSL Pinning for my demo app then app’s network traffic will look some thing like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*veLBsfvH7JlrGfz7ElsRZQ.png" /></figure><p>You won’t see the JSON response body if SSL Pinning is enabled for the app which seems secure. Now, you can see what SSL Pinning can do &amp; yes, you must have SSL Pinning in your app if you are interacting with backend server.</p><h4>SSL Pinning Using Alamofire</h4><p>If you are using Alamofire in your project then, it will be pretty easy to add SSL Pinning. There will be a <strong>session</strong> object through which you are creating any data request (or, any request), that session object needs to have a <strong>SeverTrustManager</strong> instance. That’s all, you are done with SSL Pinning.</p><p>Earlier, your code will be like —</p><pre>// Here, &#39;AF&#39; is the default session object<br>AF.request(url).response { response in<br>  //TODO: Handle Response<br>  print(response)<br>}</pre><p>Next, you need to write a method which will load the Certificate from the bundle, I am assuming you have kept your *.cer file in main bundle.</p><pre>struct Certificates {<br>    <br>    static let certificate: SecCertificate = Certificates.certificate(filename: &quot;run.mocky.io&quot;)<br>    <br>    private static func certificate(filename: String) -&gt; SecCertificate {<br>        let filePath = Bundle.main.path(forResource: filename, ofType: &quot;cer&quot;)!<br>        let data = try! Data(contentsOf: URL(fileURLWithPath: filePath))<br>        let certificate = SecCertificateCreateWithData(nil, data as CFData)!<br>        <br>        return certificate<br>    }<br>}</pre><p>Next, you need to create a new Session object which will have the Server Trust Manager instance —</p><pre><br>let certificates = [<br>        &quot;run.mocky.io&quot;:<br>            PinnedCertificatesTrustEvaluator(certificates: [Certificates.certificate],<br>                                             acceptSelfSignedCertificates: false,<br>                                             performDefaultValidation: true,<br>                                             validateHost: true)]<br><br>let serverTrustPolicy = ServerTrustManager(<br>                allHostsMustBeEvaluated: true,<br>                evaluators: certificates)<br>            <br>self.session = Session(serverTrustManager: serverTrustPolicy)</pre><p>Finally, your data request method will look something like this —</p><pre>self.session.request(url).response { response in<br>  if response.error?.isServerTrustEvaluationError {<br>    //TODO: handle when SSL Validation Failed<br>  }<br><br>  print(response)<br>}</pre><p>Now, when you run your demo with Charles Active on your Wifi Network then it will throw error ‘<strong>ServerTrustEvaluationError</strong>’ which means, your network is compromised by any proxy app or MITM.</p><h4>SSL Pinning Using URLSession</h4><p>In URLSession, you need to enable the <strong>URLSessionDelegate </strong>and implement the following method —</p><pre>private lazy var session = URLSession(configuration: .default, delegate: self,<br> delegateQueue: nil)</pre><pre>func urlSession(_ session: URLSession,<br> didReceive challenge: URLAuthenticationChallenge,<br> completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -&gt; Void)</pre><p>and, Validate the SSL Certificate data —</p><pre> func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -&gt; Void) {<br>        <br>        if let trust = challenge.protectionSpace.serverTrust,<br>           SecTrustGetCertificateCount(trust) &gt; 0 {<br>            if let certificate = SecTrustGetCertificateAtIndex(trust, 0) {<br>                let data = SecCertificateCopyData(certificate) as Data<br>                <br>                if certificates.contains(data) {<br>                    completionHandler(.useCredential, URLCredential(trust: trust))<br>                    return<br>                } else {<br>                    //TODO: Throw SSL Certificate Mismatch<br>                }<br>            }<br>            <br>        }<br>        completionHandler(.cancelAuthenticationChallenge, nil)<br>    }</pre><pre>private let certificates: [Data] = {<br>        let url = Bundle.main.url(/service/forresource: &quot;run.mocky.io&quot;, withExtension: &quot;cer&quot;)!<br>        let data = try! Data(contentsOf: url)<br>        return [data]<br>}()</pre><p>This is it, now you request will be pinned with the SSL Certificate and it case it got monitored, then you‘ll get SSL Certificate Mismatch error.</p><h4>Github</h4><p>Clone the project from `main` branch for the SSL Pinning code.<br><a href="https://github.com/greenSyntax/ssl-pinning-demo">https://github.com/greenSyntax/ssl-pinning-demo</a> 🌎</p><h4>Conclusion</h4><p>After all the pain, if we have to recall why we really need SSL Pinng in any app — <br>1. To safeguard app from MITM Attack.<br>2. Secure the communication between client &amp; server.</p><p>Yes, that all for now. Stay Safe, be it from Covid or MITM attack 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f508b5860ead" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about Frameworks in iOS]]></title>
            <link>https://medium.com/@greenSyntax/all-about-frameworks-in-ios-2295e0d195da?source=rss-edc7d1e2341------2</link>
            <guid isPermaLink="false">https://medium.com/p/2295e0d195da</guid>
            <category><![CDATA[xcframework]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Abhishek Ravi ]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 21:35:13 GMT</pubDate>
            <atom:updated>2022-09-12T21:35:13.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAuFx5IYGdz0LE_HO-5sVg.jpeg" /></figure><h4>Objective</h4><p>Lately, I was working on a task to modularise a fat codebase into a small modular components based codebase. Objective was to identify the modules which can be isolated from the main project and turn them in private frameworks (depending upon the modules). <br>Here, I am trying to replicate the same use-case in a demo project where I will keeping a class <em>AuthenticationManager (Authentication Module). </em>We are going to isolate this piece of class from the main project. Further, this component can be reused to a different project.</p><h4>Demo Project</h4><p>We will create a <em>Demo Project</em> and add two swift files under a <em>Auth</em> Group. For me, its <em>AuthenticationManager</em> and<em> AuthenticationError</em>.</p><p>//TODO: Need a Use-case Diagram</p><p>And, AuthenticationManager class has exposed three methods to sign-in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psEBK8k_LmcoFBYw_DQf3w.png" /></figure><p><em>AuthenticationError</em> will look something like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HcBvzPgLTHtjG9mdiTyCRQ.png" /></figure><p>Now, time to consume this classes from a View Layer (i.e. ViewController). <br>ViewController will hold a reference of <em>AuthenticationManger </em>and accept the completion handler cases. (Here, I am not bothered about any architecture, so bear with me).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1c3qGEgSjJTuH0HLFmcHgg.png" /></figure><h4>Roadmap</h4><p>Now, we will refactor this Demo Project and turn it into a modular one. First, we are going to drag this AuthenticationManager and AuthenticationError class to a framework so that, we can isolate our Authentication Code from our main project. Second, we will create a *.framework file which will own these two classes.<br>Third, we will create a universal xcframework which will support both device(arm64) and iOS simulators. <br>Further, we will try to move the framework source code to a Cocoapod and Carthage (May be, in a separate article).</p><h4>Create Framework</h4><p>Let’s create a <em>framework</em> project in Xcode, I am naming it as <em>Authentication</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQNk379mHN241LJUG5cUxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVykQuorCjewMd4xg174ZA.png" /></figure><p>And, Drag <em>AuthenticationManager</em> and <em>AuthenticationError </em>here under a <em>Source </em>group.</p><blockquote>Here, comes a famous interview question — <br>What is the difference between <strong>Public</strong> and <strong>Internal</strong> Access Modifier ?</blockquote><p>Public Access Modifier allows any one to access it (irrespective of any target) where, Internal Access Modifier can only be access inside their own target. <br>⚠️ So, whenever you’re making any framework make sure its Class and method should be Public not Internal. Since, Internal Access Modifier is the default one.</p><p>So, I am going to add <strong>public </strong>before all the methods and class. Make sure, you have a public initialiser for all the class to get initialised.</p><p>In Your Project’s Build Settings, Enable <strong>Build Libraries for Distribution </strong>flag as <strong>YES, </strong>then only you can distribute your framework file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eiEJXV2hOyEED8xIhrwzQ.png" /></figure><p>If your framework project is building successfully, then you are ready to distribute your framework 🎉.<br>Go to <strong>Project</strong> &gt; <strong>Show Build Folder in Finder </strong>and under <strong>Products </strong>directory you’ll see your frameworks —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3p0LqOqzAc5IN2HL9di0qw.png" /></figure><p>As you can see, there are two framework files —</p><ol><li>Debug-iphoneos which is for iOS Device</li><li>Debug-iphonesimulator which is for simulator</li></ol><p>Here comes the first limitation, of framework —</p><p>You need to import both the framework file in your consumer project to make it compatible for iOS Device and Simulator at the same time. This limitation is overcome by <strong>xcframework </strong>which supports both the architecture.</p><p>Next, we will try with simulator’s framework in our Consumer Project. To do that, we will move to our Demo Project i.e. <strong>ConsumerProject</strong> and delete the <strong>Auth </strong>group where we had AuthenticationManager + AuthenticationError. After removing, ViewController will start throwing compiler error as there is no AuthenticationManager Class in the project visibility. <br>To fix this, we will drag and drop the framework file in the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezmHdv28mgHKlDJzKGX2tA.png" /></figure><p>Add <strong>import Authentication </strong>statement, so that you can access the framework files. After importing, there will be no compile time error on <em>AutheticationManager</em>.</p><p>📦 Till now, we have created Authentication framework file which can distributed easily to the world, but there is one limitation in this technique is that — separate simulator and device framework files . So, we need to identify some way-out, where single framework file can do the job for simulator and iOS arm64 devices. Answer is — <strong>xcframework</strong>.</p><h4>Convert into xcframework</h4><p>So, xcframework is nothing but a universal architecture independent framework file. Here, we are only bothered about arm64 device and simulator framework. We will create binary for both the architecture and then generate the xcframework bundle using terminal. To make it easy, we have <a href="https://gist.github.com/greenSyntax/4faa41e4ff75426cd62a1cb466197759#file-xcframework_build-sh"><em>build</em></a>_xcframework<em>.sh</em> script with us which generate a xcframework in /build directory under your framework directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5226904db56cb01094ba8738eebc86e1/href">https://medium.com/media/5226904db56cb01094ba8738eebc86e1/href</a></iframe><p>Create a sh file inside the framework root directory with whatever name you wish. Mine was <a href="https://gist.github.com/greenSyntax/4faa41e4ff75426cd62a1cb466197759#file-xcframework_build-sh"><strong><em>build</em></strong></a><strong>_xcframework<em>.sh</em></strong><em> </em>and open terminal go the framework directory and execute <strong>sh build_framework.sh</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mO6EvRwx3N039LifFqqntQ.png" /></figure><p>On successful archiving, you will have xcframework file inside the build directory. This single xcframework file is compatible for simulator and arm64 devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*jZYibb11WLmpB3F1Op0XeA.png" /></figure><p><strong>✅ Note </strong>: If you are asked to share any framework file, always prefer sharing xcframework. Since, it supports multiple architecture, size is obviously greater than any *.framework file.</p><p>Let’s import the xcframework file in your demo ConsumerProject and build the project. Yes, its working fine 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HBU7KPvQRiAlAzhSf7um6g.png" /></figure><p>And, make sure embed your framework to the bundle else it will crash on release archive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ToEObpqEKDx3rfpaWZ__2A.png" /></figure><h4><strong>Conclusion</strong></h4><p>Here, we explored about the framework and xframework files. In next part, we will explore about the dynamic framework and it’s linking to nested framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2295e0d195da" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>