<?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 lalit kant on Medium]]></title>
        <description><![CDATA[Stories by lalit kant on Medium]]></description>
        <link>https://medium.com/@lalitkya31?source=rss-bc770f143f17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TwvwOfJF_8UumbQX09YDig.jpeg</url>
            <title>Stories by lalit kant on Medium</title>
            <link>https://medium.com/@lalitkya31?source=rss-bc770f143f17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:11:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lalitkya31/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[Top 20 iOS interview questions for beginner to Intermediate level]]></title>
            <link>https://medium.com/@lalitkya31/top-20-ios-interview-questions-for-beginner-to-intermediate-level-712dcf086654?source=rss-bc770f143f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/712dcf086654</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[lalit kant]]></dc:creator>
            <pubDate>Sun, 01 May 2022 20:47:32 GMT</pubDate>
            <atom:updated>2022-05-20T05:03:53.705Z</atom:updated>
            <content:encoded><![CDATA[<p>Now a days interview standard is very high, even for freshers. So, we should concentrate more on the basics of Swift.</p><blockquote>In this story I am going to share knowledge on <strong>Swift basics</strong>, some important <strong>output check questions</strong> which are mostly asked during interview. As we move on to questions, it will be more interesting.</blockquote><blockquote><strong>So, stay tuned.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*fcwLWixk10G27dEqiHOM-Q.gif" /><figcaption>Let’s start. Image credit <a href="https://tenor.com/view/despicable-me-minions-lets-get-started-happy-excited-gif-4767352">here</a></figcaption></figure><p>With no further adieu lets’s get started.</p><blockquote><strong>1. What is the difference between Swift and Objective-C. Which one is better and why?</strong></blockquote><p><strong>Answer</strong>: Here we have few differences between Objective-C and Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*0tUZmGSUkkEGoVcWs9XaeA.png" /><figcaption>Image credit <a href="https://mlsdev.com/blog/swift-vs-objective-c">here</a></figcaption></figure><p>Both Swift and Objective has its pros and cons. But due to following reason Swift is plus over Objective C.</p><ol><li>Objective-C is outdated compared to Swift and lacks modern tool.</li><li>Swift is faster, Safer, more readable, reliable</li><li>Swift need less code and its close to other modern languages.</li><li><strong>Apple ongoing focus</strong></li></ol><p>Reference <a href="https://mlsdev.com/blog/swift-vs-objective-c">link</a></p><blockquote><strong>2. What are iOS application states?</strong></blockquote><p><strong>Answer</strong>:</p><ol><li><strong><em>Non-running</em></strong> — The app is not running.</li><li><strong><em>Inactive</em></strong> — The app is running in the foreground, but not receiving events. An iOS app can be placed into an inactive state, for example, when a call or SMS message is received.</li><li><strong><em>Active</em></strong> — The app is running in the foreground, and receiving events.</li><li><strong><em>Background</em></strong> — The app is running in the background, and executing code.</li><li><strong><em>Suspended</em></strong> — The app is in the background, but no code is being executed.</li></ol><p>Reference <a href="https://www.techrepublic.com/article/understand-the-states-and-transitions-of-an-ios-app/">link</a>.</p><blockquote><strong>3. What is view controller lifecycle?</strong></blockquote><p><strong>Answer</strong>: Lifecycle events order</p><p>init(coder:)<br>(void)loadView<br>(void)viewDidLoad<br>(void)viewWillAppear<br>(void)viewDidAppear<br>(void)didReceiveMemoryWarning<br>(void)viewWillDisappear<br>(void)viewDidDisappear</p><p>Reference <a href="https://www.codementor.io/@hemantkumar434/view-controller-lifecycle-ios-applications-7oyju9lp6">link</a>.</p><p>Let’s start with basic questions…..</p><blockquote><strong>4. What is optional in Swift?</strong></blockquote><p><strong>Answer</strong>: You use the Optional type whenever you use optional values, even if you never type the word Optional. Swift’s type system usually shows the wrapped type’s name with a trailing question mark (?) instead of showing the full type name. For example, if a variable has the type Int?, that’s just another way of writing Optional&lt;Int&gt;. The shortened form is preferred for ease of reading and writing code.</p><p>Reference <a href="https://developer.apple.com/documentation/swift/optional">Link</a></p><blockquote><strong>5. Difference between guard let and If let ?</strong></blockquote><p>Answer:</p><p><strong>Guard let</strong></p><ul><li>A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.</li><li>The value of any condition in a guard statement must be of type Bool or a type bridged to Bool. The condition can also be an optional binding declaration.</li></ul><p>guard condition else { //Generally return }</p><pre>func submit() {</pre><pre>guard let name = nameField.text else {</pre><pre>show(&quot;No name to submit&quot;)</pre><pre>return</pre><pre>}</pre><p><strong>If let</strong></p><ul><li>Also popular as optional binding</li><li>For accessing optional object we use if let</li></ul><pre>if let roomCount = optionalValue {</pre><pre>print(&quot;roomCount available&quot;)</pre><pre>} else {</pre><pre>print(&quot;roomCount is nil&quot;)</pre><pre>}</pre><blockquote><strong>6. Can we have Tuples with single value?</strong></blockquote><p>Answer: No.</p><blockquote><strong>7. List control transfer statement in Swift.</strong></blockquote><p>Answer:</p><ul><li>continue</li><li>break</li><li>fallthrough</li><li>return</li><li>throw</li></ul><blockquote><strong>8. How to modify parameter values of a function? Means what’s the way for a function to have an effect on parameter value outside of the scope of its function body.</strong></blockquote><p><strong>Answer</strong>: <strong>In-out</strong> parameters are an alternative way for a function to have an effect outside of the scope of its function body.</p><p>Example:</p><pre>func swapTwoInts(_ a: inout Int, _ b: inout Int) {</pre><pre> let temporaryA = a</pre><pre> a = b</pre><pre> b = temporaryA</pre><pre>}</pre><pre>var someInt = 3</pre><pre>var anotherInt = 107</pre><pre>swapTwoInts(&amp;someInt, &amp;anotherInt)</pre><blockquote><strong>9. Can we have a nested function in swift?</strong></blockquote><p><strong>Answer:</strong> Yes</p><blockquote><strong>10. What is auto closure and when to use auto closure in Swift?</strong></blockquote><p><strong>Answer:</strong> An <strong><em>autoclosure</em></strong> is a closure that’s automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it. This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.</p><p><strong>Usage: </strong>An autoclosure lets you delay evaluation, because the code inside isn’t run until you call the closure. Delaying evaluation is useful for code that has side effects or is computationally expensive, because it lets you control when that code is evaluated. The code below shows how a closure delays evaluation.</p><pre>var customersInLine = [“Chris”, “Alex”, “Ewa”, “Barry”, “Daniella”]</pre><pre>print(customersInLine.count) // Prints “5”</pre><pre>let customerProvider = { customersInLine.remove(at: 0) }</pre><pre>print(customersInLine.count) // Prints “5”</pre><pre>print(“Now serving \(customerProvider())!”) // Prints “Now serving Chris!”</pre><pre>print(customersInLine.count) // Prints “4”</pre><p>Reference <a href="https://docs.swift.org/swift-book/LanguageGuide/Closures.html">Link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*7DEHsql2_r4pAIcBvSXdSQ.gif" /><figcaption>Gif <a href="https://giphy.com/explore/halfway">link</a></figcaption></figure><h3>Thanks for reading halfway.. Very helpful question are coming up now.</h3><blockquote><strong>11. What is retain cycle and memory leak? — Mostly asked</strong></blockquote><p><strong>Answer</strong>: A <strong>memory leak</strong> in iOS is when an amount of allocated space in memory cannot be deallocated due to retain cycles. Since Swift uses <a href="https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html">Automatic Reference Counting (ARC)</a>, a <strong>Retain cycle</strong> occurs when two or more objects hold strong references to each other. As a result these objects retain each other in memory because their retain count would never decrement to 0, which would prevent <a href="https://docs.swift.org/swift-book/LanguageGuide/Deinitialization.html">deinit</a> from ever being called and memory from being freed.</p><p>Reference <a href="https://betterprogramming.pub/retain-cycles-and-memory-management-in-swift-fb6226165b17">link</a></p><blockquote><strong>12. What are higher order functions and how to use them?</strong></blockquote><p><strong>Answer: </strong>A higher-order function is <strong>a function that takes one or more functions as arguments or returns a function as its result</strong>. Here are some swift higher-order functions.</p><ul><li>map</li><li>compactMap</li><li>flatMap</li><li>filter</li><li>reduce</li><li>forEach</li><li>contains</li><li>removeAll</li><li>sorted</li><li>split</li></ul><p>Reference <a href="https://www.appcoda.com/higher-order-functions-swift/">link</a></p><blockquote><strong>13. What are generics in Swift?</strong></blockquote><p><strong>Answer:</strong> <strong><em>Generic code</em></strong> enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.</p><p>Example:</p><pre>func swapTwoValues&lt;T&gt;(_ a: inout T, _ b: inout T) {</pre><pre> let temporaryA = a</pre><pre> a = b</pre><pre> b = temporaryA</pre><pre>}</pre><p>In the two examples below, T is inferred to be Int and String respectively:</p><pre>var someInt = 3</pre><pre>var anotherInt = 107</pre><pre>swapTwoValues(&amp;someInt, &amp;anotherInt)</pre><pre>// someInt is now 107, and anotherInt is now 3</pre><pre>var someString = “hello”</pre><pre>var anotherString = “world”</pre><pre>swapTwoValues(&amp;someString, &amp;anotherString)</pre><pre>// someString is now “world”, and anotherString is now “hello”</pre><blockquote><strong>14. What is different ways of concurrent operations in Swift?</strong></blockquote><p><strong>Answer:</strong> We have following ways of concurrent opeations in Swift.</p><ol><li>DispatchQueue</li></ol><p>2. Operation and OperationQueues</p><p>3. Swift Concurrency</p><p>Reference <a href="https://betterprogramming.pub/concurrency-in-ios-and-swift-guide-50443ce5b0f5">link</a></p><blockquote><strong>15. What will be output of num variable following code?</strong></blockquote><blockquote>var num = -1</blockquote><blockquote>num = +num</blockquote><p><strong>Answer:</strong> -1</p><blockquote><strong>16. What will be output of _value in following code?</strong></blockquote><blockquote><strong>let _value = 1.0_1111_1?</strong></blockquote><p><strong>Answer: </strong>1.011111</p><blockquote><strong>17. How we can set value of a variable in the scope of it main class only?</strong></blockquote><p><strong>Answer: </strong>Make the variable private (set)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7DdQHLOs4aW2a7tn15-1xA.png" /></figure><blockquote><strong>18. Write code to create a singleton class.</strong></blockquote><p><strong>Answer:</strong></p><pre>class Student {</pre><pre>static let shared = Student()</pre><pre>private init() {}</pre><pre>}</pre><pre>//Use:</pre><pre>let studentInstance = Student.shared</pre><blockquote><strong>19. What will be printed on executing this code?</strong></blockquote><blockquote>var a = 0</blockquote><blockquote>var b = 0</blockquote><blockquote>let closure = { [a] in</blockquote><blockquote>print(a)</blockquote><blockquote>print(b)</blockquote><blockquote>}</blockquote><blockquote>a = 10</blockquote><blockquote>b = 10</blockquote><blockquote>closure()</blockquote><p><strong>Answer:</strong></p><p>0</p><p>10</p><blockquote><strong>20. Write your own sorting algorithm in swift.</strong></blockquote><p><strong>Answer:</strong> We have difference type of sorting techniques but to provide best result we can use Merge Sort or Quick Sort.</p><p>Here we have link to check <a href="https://medium.com/@lalitkya31/sorting-algorithm-in-swift-part-1-bubble-sort-7bd7fa0a3690">Bubble Sort</a>, <a href="https://medium.com/@lalitkya31/sorting-algorithm-in-swift-insertion-sort-part-2-17e3e636e5a1">Insertion Sort</a> and <a href="https://medium.com/@lalitkya31/sorting-algorithm-in-swift-merge-sort-part-3-336811f63ab2">Merge Sort</a> code.</p><p><strong>Conclusion: </strong>Even if you are fresher or experience. It’s very important to keep updated with Basic of programming. I hope my blog helps you to crack your interview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*MOnnY6MEE9g_RVMuQzbTRw.gif" /><figcaption>Image credit <a href="http://blazonsart.com/good_luck-9.html">link</a></figcaption></figure><h4>Best of luck!!!!</h4><h3>Happy Coding…</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=712dcf086654" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithm in Swift: Merge Sort (Part — 3)]]></title>
            <link>https://medium.com/@lalitkya31/sorting-algorithm-in-swift-merge-sort-part-3-336811f63ab2?source=rss-bc770f143f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/336811f63ab2</guid>
            <category><![CDATA[merge-sort]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[lalit kant]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 17:57:04 GMT</pubDate>
            <atom:updated>2022-04-24T17:57:04.755Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sorting Algorithm in Swift: Merge Sort (Part — 3)</h3><p>We are now heading towards the fast sorting algorithms and which are very useful in sorting large arrays with best time and space complexities.</p><p>Before we move forward, If you want to start with basic sorting algorithms then please goto <a href="https://medium.com/@lalitkya31/sorting-algorithm-in-swift-part-1-bubble-sort-7bd7fa0a3690">part — 1</a> and <a href="https://medium.com/@lalitkya31/sorting-algorithm-in-swift-insertion-sort-part-2-17e3e636e5a1">part-2</a> of algorithms series.</p><blockquote>One of the algorithm which is very popular and Widely used by many Standard library <strong>i.e.</strong> <strong>Merge Sort. Which is based on Divide and conquer approach!!</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*yc-EYAAYPA3Q4Ru95-G93Q.gif" /></figure><h3>Merge Sort (Fast sorting algorithm)</h3><p>Let’s start quickly on how does Merge sort work and what is quicker way to implement in swift.</p><h4>Steps:</h4><ol><li>Put the numbers in unsorted array.</li><li>Create a function which take the unsorted array.</li><li>Divide unsorted array into 2 arrays. Now you have 2 unsorted arrays.</li><li>Keep splitting the array until their count goes down to 1 (Use recursion todo this)</li><li>Then conquer the array together by pairing then sequentially.</li><li>Put the content in sorted order on each merge. Its easy because each individual array is already sorted.</li></ol><h4>Example:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFp0gcdssPn74B812ILY1Q.png" /><figcaption>Image picked from <a href="https://www.java67.com/2018/03/mergesort-in-java-algorithm-example-and.html">here</a></figcaption></figure><h4>Code snippet:</h4><pre>// MARK: Merge Sort</pre><pre>/// I have done Merge sort in Ascending order</pre><pre>/// If we want to change sorting order of string then change comparator operator &lt; to &gt;</pre><pre>///</pre><pre>func mergeSort&lt;T: Comparable&gt;(list:[T]) -&gt; [T] {</pre><pre> guard list.count &gt; 1 else {</pre><pre>  return list</pre><pre>  }</pre><pre> let leftList = Array(list[0..&lt;list.count/2])</pre><pre> let rightList = Array(list[list.count/2..&lt;list.count])</pre><pre> return merge(left: mergeSort(list:leftList), right:    mergeSort(list:rightList))</pre><pre>}</pre><pre>func merge&lt;T: Comparable&gt;(left:[T], right:[T]) -&gt; [T] {</pre><pre>  var mergedList = [T]()</pre><pre>  var left = left</pre><pre>  var right = right</pre><pre>  while left.count &gt; 0 &amp;&amp; right.count &gt; 0 {</pre><pre>    if left.first! &lt; right.first! {</pre><pre>       mergedList.append(left.removeFirst())</pre><pre>    } else {</pre><pre>      mergedList.append(right.removeFirst())</pre><pre>    }</pre><pre> }</pre><pre> return mergedList + left + right</pre><pre>}</pre><h4>Usage:</h4><pre>var intArrayToBeSorted = [1,1,45,23,11,76,25,98,34,56]</pre><pre>print(mergeSort(list: intArrayToBeSorted))</pre><pre>var doubleArrayToBeSorted = [1,1.5,45.1,23.22,11,76,25,98,34,56]</pre><pre>print(mergeSort(list: doubleArrayToBeSorted))</pre><pre>// Empty space is present in the end of sorted string<br>var stringToBeSorted = &quot;Sort Bubbles&quot;</pre><pre>var stringToArray = Array(stringToBeSorted)</pre><pre>print(mergeSort(list: stringToArray))</pre><h3>Complexities:</h3><p><strong>Best Case:</strong> O(n log n)</p><p><strong>Worst Case:</strong> O(n log n)</p><p><strong>Average Case:</strong> O(n log n)</p><h3>When to use:</h3><ul><li>Can be used for external sorting.</li><li>Highly parallelizable</li><li>Stable sort</li></ul><h3>Cons:</h3><ul><li>It’s marginally slow to Quick sort as in Merge Sort there is temporary “working” array equal in size to the array being sorted.</li><li>Not best in space management.</li></ul><blockquote>Merge Sort looks scary but its pretty straight forward.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*rsav_omH1Ggl4pQlP27jlg.jpeg" /><figcaption>Image used from <a href="https://memegenerator.net/instance/46424211/celebrate-minions-we-did-it">here</a></figcaption></figure><h3><strong>Happy Coding!!</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=336811f63ab2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithm in Swift: Insertion Sort(Part — 2)]]></title>
            <link>https://medium.com/@lalitkya31/sorting-algorithm-in-swift-insertion-sort-part-2-17e3e636e5a1?source=rss-bc770f143f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/17e3e636e5a1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[insertion-sort]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[lalit kant]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 17:09:57 GMT</pubDate>
            <atom:updated>2022-04-24T17:09:57.225Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sorting Algorithm in Swift: Insertion Sort(Part — 2)</h3><blockquote>Let’s start with next algorithm Insertion Sort. If you want to explore on Bubble sort then please refer to <a href="https://medium.com/@lalitkya31/sorting-algorithm-in-swift-part-1-bubble-sort-7bd7fa0a3690"><strong>Part-1</strong></a> session of this series.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBvQ04OQ0x-N_Z2R_Dme8w.jpeg" /></figure><h3>Insertion Sort:</h3><p>Insertion sort is a sorting technique which follow below steps:</p><ol><li>First put unsorted number in an array.</li><li>Insert array to new number array</li><li>Then pick any number from the pile, insert that number to new array and start comparing that number from the last value of new array.</li><li>if picked number from array is less than the number from the new array then simply swap the number.</li><li>Repeat the process until complete arrays is sorted.</li></ol><p><strong>Let’s take and example</strong></p><p>[3,4,5,1,0,8,1]</p><p><strong>Below are sorting steps</strong></p><p>[3]|[4,5,1,0,8,1]</p><p>[3,4]|[5,1,0,8,1]</p><p>[3,4,5]|[1,0,8,1]</p><p>[1,3,4,5]|[0,8,1]</p><p>[0,1,3,4,5]|[8,1]</p><p>[0,1,3,4,5,8]|[1]</p><p>[0,1,3,4,5,8,1]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9uiibw2fXnlhRF32OngfUw.png" /><figcaption><strong>Insertion Sort</strong></figcaption></figure><h3>Code snippet:</h3><pre>/// Performs the Insertion sort algorithm to a given array</pre><pre>///</pre><pre>/// - Parameter array: the array to be sorted, conatining elements that conform to the Comparable protocol</pre><pre>/// - Returns: a sorted array containing the same elements</pre><pre>func insertionSort&lt;T: Comparable&gt;(_ array: [T]) -&gt; [T] {</pre><pre> var sortedArray = array</pre><pre> for index in 1..&lt;sortedArray.count {</pre><pre>  var currentIndex = index</pre><pre>  let temp = sortedArray[currentIndex]</pre><pre>  while currentIndex &gt; 0 &amp;&amp; temp &lt; sortedArray[currentIndex - 1] {</pre><pre>    sortedArray[currentIndex] = sortedArray[currentIndex - 1]</pre><pre>    currentIndex -= 1</pre><pre> }</pre><pre> sortedArray[currentIndex] = temp</pre><pre>}</pre><pre> return sortedArray</pre><pre>}</pre><p>Usage:</p><pre>print(insertionSort([3,4,5,1,0,8,1])</pre><h3>Complexities:</h3><p><strong>Best Case:</strong> O(n) When arrays is in sorted order</p><p><strong>Worst Case:</strong> O(n2) when we try to sort ascending order of array but actually array is in Descending order.</p><p><strong>Average Case:</strong> O(n2) When try to sort jumbled order value array. Insertion sort is actually very fast for sorting small arrays.</p><h3>When to use</h3><ul><li><strong>Insertion sort is actually very fast for sorting small arrays. Some library prefer to use Insertion sort for small array(count less then 10)</strong></li><li>Complexity is not a concern</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*1b3Q-MJajrVh64fuP2AmKA.gif" /><figcaption><strong>Happy Coding</strong></figcaption></figure><h3>Happy Coding !!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17e3e636e5a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting Algorithm in Swift: Part — 1 Bubble Sort]]></title>
            <link>https://medium.com/@lalitkya31/sorting-algorithm-in-swift-part-1-bubble-sort-7bd7fa0a3690?source=rss-bc770f143f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bd7fa0a3690</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[bubble-sort]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[lalit kant]]></dc:creator>
            <pubDate>Sat, 23 Apr 2022 19:56:01 GMT</pubDate>
            <atom:updated>2022-04-24T17:58:58.739Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sorting Algorithm in Swift: Bubble Sort (Part — 1)</h3><p>Algorithms are very important in developer life. It help us to write powerful code. All Giant companies like Google, Microsoft, Apple, Facebook in start judge you based on your Logical and Algorithmic skills.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*sao6K3zslMVdUzn_rfrD5w.png" /><figcaption><strong>Algorithms are simple</strong></figcaption></figure><p>Many developers face problem in writing Algorithms in Swift language. So, to help all iOS developers I am writing Sorting Algorithms in Swift.</p><p>I am covering mostly used sorting algorithms.</p><p>I will start this series with simple Algo first… then….. so on…..</p><ol><li>Bubble Sort(Least preferred sorting algorithm)</li><li><a href="https://medium.com/@lalitkya31/sorting-algorithm-in-swift-insertion-sort-part-2-17e3e636e5a1">Insertion Sort (Basic sorting algorithm)</a></li><li><a href="https://medium.com/@lalitkya31/sorting-algorithm-in-swift-merge-sort-part-3-336811f63ab2">Merge Sort(Fast sorting algorithm)</a></li><li>Quick Sort(Fast sorting algorithm) — Coming soon</li></ol><h3>Bubble Sort:</h3><p><strong>Bubble sort</strong> is sorting algorithm that compares two adjacent elements and swaps them until they are not in the intended order.</p><p>Just like the movement of air bubbles in the water that rise up to the surface, each element of the array move to the end in each iteration. Therefore, it is called a bubble sort. Sometime it is called as sinking sort.</p><h4>Implementation(e.g. Descending Order):</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CaoyjQgxBINh1pxHqSidnA.jpeg" /><figcaption><strong>Bubble Sort</strong></figcaption></figure><ol><li>Start iterations for main array</li><li>Starting from the first index, compare the first and the second elements by adding nested loop.</li><li>Second nested loop will run from next index of sorted indexes of main array.</li><li>Then If the first element is less than the second element, they are swapped.</li><li>Now, compare the second and the third elements. Swap them if they are not in order.</li><li>The above process goes on until the last element.</li></ol><h4>Here is Code to use it:</h4><p>The Solution I have done is to sort all data type of array values e.g. string, Integers etc.</p><p>This implementation little more optimised as we are comparing inner loop index data with main array index .</p><pre>// MARK: Bubble Sort</pre><pre>/// I have done Merge sort in Decensding order</pre><pre>/// /// If we want to change sorting order of string then change comparator operator &gt; to &lt;</pre><pre>func bubbleSort&lt;T: Comparable&gt;(arrTobeSorted: inout [T]) {</pre><pre>for i in 0..&lt;arrTobeSorted.count</pre><pre>{</pre><pre> for j in i..&lt;arrTobeSorted.count</pre><pre>  {</pre><pre>   if arrTobeSorted[i] &lt; arrTobeSorted[j]</pre><pre>    {</pre><pre>      let tempNum = arrTobeSorted[i]</pre><pre>      arrTobeSorted[i] = arrTobeSorted[j]</pre><pre>      arrTobeSorted[j] = tempNum</pre><pre>    }</pre><pre>  }</pre><pre> }</pre><pre>}</pre><h3>How to use</h3><pre><br>var intArrayToBeSorted = [1,1,45,23,11,76,25,98,34,56]</pre><pre>bubbleSort(arrTobeSorted: &amp;intArrayToBeSorted)</pre><pre>print(intArrayToBeSorted)</pre><pre>var doubleArrayToBeSorted = [1,1.5,45.1,23.22,11,76,25,98,34,56]</pre><pre>bubbleSort(arrTobeSorted: &amp;doubleArrayToBeSorted)</pre><pre>print(doubleArrayToBeSorted)</pre><pre>var stringToBeSorted = &quot;Sort Bubbles&quot;</pre><pre>var stringToArray = Array(stringToBeSorted)</pre><pre>bubbleSort(arrTobeSorted: &amp;stringToArray)</pre><pre>// Empty space is present in the end of sorted string</pre><pre>print(String(stringToArray))</pre><h4>Complexities:</h4><p><strong>Best Case:</strong> O(n) When arrays is in sorted order</p><p><strong>Worst Case:</strong> O(n2) when we try to sort ascending order of array but actually array is in Descending order.</p><p><strong>Average Case:</strong> O(n2) When try to sort jumbled order value array.</p><h3><strong>When to use</strong></h3><ul><li>Complexity is not a concern</li><li>Simple code is preferred</li></ul><h3>Happy Coding !!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bd7fa0a3690" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS: Dependency Injection aka Inversion of control]]></title>
            <link>https://medium.com/@lalitkya31/ios-dependency-injection-aka-inversion-of-control-e2e325d66f8?source=rss-bc770f143f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2e325d66f8</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[lalit kant]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 09:19:02 GMT</pubDate>
            <atom:updated>2022-04-17T09:19:02.601Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dYdI1lh2Fa6HjeCyntszaA.jpeg" /><figcaption><strong>Dependency Injection</strong></figcaption></figure><h3><strong>Inversion-of-Control:</strong></h3><p>The <strong>Inversion-of-Control (IoC)</strong> pattern, is about providing <em>any kind</em> of callback (which &quot;implements&quot; and/or controls reaction), instead of acting ourself directly (in other words, inversion and/or redirecting control to external handler/controller).</p><blockquote><em>For example, rather than having the application call the implementations provided by a </em>library<em> (also know as </em>toolkit<em>), a </em>framework<em> calls the implementations provided by the application.</em></blockquote><h3><strong>Dependency-Injection(Specific version of IoC):</strong></h3><p>The <strong>Dependency-Injection (DI)</strong> pattern is a more specific version of <strong>IoC</strong> pattern, where implementations are passed into an object through constructors/setters/service lookups, which the object will &#39;depend&#39; on in order to behave correctly.</p><blockquote><em>Every </em><em>DI implementation can be considered </em><em>IoC, but one should not call it </em><em>IoC, because implementing Dependency-Injection is harder than callback (Don&#39;t lower your product&#39;s worth by using general term &quot;IoC&quot; instead).</em></blockquote><h3><strong>Why and when?? </strong>Dependency-Injection<strong>?</strong></h3><ol><li>When you want to make code loosely coupled use DI.</li><li>When you want to “mock” or fake behavior in your code during development.</li><li>When you want code to be unit tested without dependency of a complete module features.</li><li>More reusable code.</li><li>More readable code.</li></ol><h4>Example:</h4><ul><li>Let’s say in our project we are fetching data from local DB but later there is a requirement to fetch the data from some api.</li><li>So, to avoid direct dependency on your main class file(Tightly coupled) we can make a protocol for fetching data.</li><li>With protocol we can make the code Loosely coupled.</li><li>By extending same protocol we can make independent calls from DB and Api’s.</li></ul><h3>Sample:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*Ln95M4huwcuBXRmb1czp5Q.gif" /></figure><p>I have build a sample app with following steps:</p><ul><li>We need to parse this <a href="https://github.com/LalitKY/DependencyInjection/blob/main/DependencyInjection/MockJson/jsonFile.json">file</a>.</li><li>We need to show a list of items available in file.</li><li>There is a “timeRemaining” key so we need to run a timer for the remaining time and update the same on the UI.</li><li>After completing the time we need to show an alert “Do you want to delete this item” with the “cancel” or “delete” button.</li><li>if you tap on “delete” row will be deleted from the list.</li></ul><p><strong>Additional Terminalogy in Sample:</strong></p><p>MVVM, <a href="https://github.com/LalitKY/DependencyInjection/blob/main/DependencyInjection/JsonManager/JsonLoaderManager.swift">Generics</a>, <a href="https://github.com/LalitKY/DependencyInjection/blob/main/DependencyInjection/ReactiveBinder/Bindable.swift">Bindable notifier</a></p><h3>Where we have DI in Sample:</h3><h4>TimerDataInject.swift</h4><p><a href="https://github.com/LalitKY/DependencyInjection/blob/main/DependencyInjection/JsonManager/TimerDataInject.swift">DependencyInjection/TimerDataInject.swift at main · LalitKY/DependencyInjection</a></p><p>hold the responsibility to inject data in ViewModel(TimerVM.swift) file.</p><pre>class TimerDataInject {</pre><pre>var timerFileData: GetTimerFileData</pre><pre>init(fileData: GetTimerFileData) {</pre><pre>self.timerFileData = fileData</pre><pre>}</pre><pre>func getTimerData(completion: @escaping (Result&lt;[TimerDataModal]?, Error&gt;) -&gt; ()) {</pre><pre>self.timerFileData.getTimerData(completion: completion)</pre><pre>}</pre><pre>}</pre><ul><li>TimerDataInject.swift has GetTimerFileData(Protocol) initialiser which is responsible for providing data to ViewModel via TimerDataInject.swift class.</li><li>getTimerData method fetch data from GetTimerFileData extension methods.</li></ul><h4>JsonLoaderManager.swift</h4><p><a href="https://github.com/LalitKY/DependencyInjection/blob/main/DependencyInjection/JsonManager/JsonLoaderManager.swift">DependencyInjection/JsonLoaderManager.swift at main · LalitKY/DependencyInjection</a></p><h4>hold <strong>GetTimerFileData</strong> protocol, <strong>LoadDataFromJsonServiceManager</strong> and <strong>LoadDataFromApiServiceManager </strong>extensions</h4><ul><li><strong>GetTimerFileData </strong>responsible to provide data from its extension structs based on requirement.</li></ul><pre>protocol GetTimerFileData {</pre><pre>func getTimerData(completion: @escaping (Result&lt;[TimerDataModal]?, Error&gt;) -&gt; ())</pre><pre>}</pre><ul><li><strong>LoadDataFromJsonServiceManager </strong>responsible to provide data from json file.</li></ul><pre>struct LoadDataFromJsonServiceManager: GetTimerFileData {</pre><pre>func getTimerData(completion: @escaping (Result&lt;[TimerDataModal]?, Error&gt;) -&gt; ()) {</pre><pre>self.loadJson(fileName: Constants.fileName, completion: completion)</pre><pre>}</pre><pre>private func loadJson&lt;T: Decodable&gt;(fileName: String, completion: @escaping (Result&lt;T?, Error&gt;) -&gt; ()) {</pre><pre>if let url = Bundle.main.url(/service/forresource: fileName, withExtension: &quot;json&quot;) {</pre><pre>do {</pre><pre>let data = try Data(contentsOf: url)</pre><pre>let decoder = JSONDecoder()</pre><pre>let jsonData = try decoder.decode(T.self, from: data)</pre><pre>return completion(.success(jsonData))</pre><pre>} catch {</pre><pre>print(&quot;error:\(error)&quot;)</pre><pre>return completion(.failure(error))</pre><pre>}</pre><pre>}</pre><pre>return</pre><pre>}</pre><pre>}</pre><ul><li><strong>LoadDataFromApiServiceManager </strong>responsible to provide data from api’s. We can write code to fetch data from some api.</li></ul><pre>struct LoadDataFromApiServiceManager: GetTimerFileData {</pre><pre>func getTimerData(completion: @escaping (Result&lt;[TimerDataModal]?, Error&gt;) -&gt; ()) {</pre><pre>completion(.success([TimerDataModal.init()]))</pre><pre>}</pre><pre>}</pre><p><strong>Usage:</strong></p><p>In TimerVM.swift class below is code for consumption of above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAIbIHDDMNL45xwK_PykqA.png" /></figure><h3>Conclusion:</h3><p>IoC is not DI but DI is part of IoC. In this blog we get to know about Dependency Injection, how to consume Dependency Injection.</p><p>Based on our project needs we can use consume third party DI tools as well like <a href="https://github.com/Swinject/Swinject"><strong>Swinject</strong></a><strong>.</strong></p><p>Download the code from <a href="https://github.com/LalitKY/DependencyInjection">here</a>. Please write your thoughts in comments section. I will be happy to answer.</p><p><strong>Happy Coding.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*8DnKuYZrgiRSrHy1S1L6cQ.gif" /><figcaption><strong>Happy Coding!!</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2e325d66f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS: Router/Routing with MVVM]]></title>
            <link>https://medium.com/@lalitkya31/ios-router-routing-with-mvvm-84ea115e15c6?source=rss-bc770f143f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/84ea115e15c6</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[router]]></category>
            <category><![CDATA[solid-design-principles]]></category>
            <dc:creator><![CDATA[lalit kant]]></dc:creator>
            <pubDate>Mon, 28 Mar 2022 20:15:38 GMT</pubDate>
            <atom:updated>2022-04-24T18:03:48.760Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*JmZKrfVpmZOPYZKSeAvlrQ.jpeg" /></figure><p>We have been using MVC, MVP and MVVM, VIP and VIPER, We always try to write out business logic in separate classes/files. But we are not bother about routing or navigation part segregation except in <a href="https://github.com/LalitKY/MVVMR"><strong>VIPER</strong></a><strong> </strong>Architecture. Let us Go…..</p><blockquote><strong>Router:</strong> It has all navigation logic for describing which screens are to be shown when. It is normally written as a wireframe.</blockquote><h3><strong>Why?? Router needed ?</strong></h3><ol><li>Router is a need of all architecture today as our navigation part is still stuck in View controllers.</li><li>This make our navigation Loosely coupled.</li><li>It follows SOLID design principles.</li></ol><h3><strong>Sample</strong></h3><p>We are using MVVM design pattern and over the top of it we will add Router which become<strong> MVVMR Architecture</strong></p><ol><li>We will see list of Employees in home screen</li><li>On tapping on a cell in home screen it goes to Employee detail screen.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*HKcpdyK7lMd_Pfp8vDpZVw.jpeg" /><figcaption>Happy Coding</figcaption></figure><p>Lets talk more about router part as MVVM Architecture part you can see in sample.</p><p><strong>Router class has basic 4 sections:</strong></p><ol><li><em>Creating module or class:</em></li><li><em>Create Router class</em></li><li><em>Create Router Protocol</em></li><li><em>Extend Router(implement router protocols methods in Router extension)</em></li></ol><p>Employee list Router example:</p><ol><li><strong><em>Creating module or classs:</em></strong></li></ol><pre>class EmployeeListModule {</pre><pre>func createModule() -&gt; UIViewController {</pre><pre>let storyboard = UIStoryboard(name: &quot;Main&quot;, bundle: nil)</pre><pre>let empVC = storyboard.instantiateViewController(withIdentifier: &quot;ViewController&quot;) as! ViewController</pre><pre>empVC.employeeViewModel.router = EmployeeListRouter()</pre><pre>empVC.employeeViewModel.router?.viewController = empVC</pre><pre>return empVC</pre><pre>}</pre><pre>}</pre><p>Employee list module is to create instance of view controller.</p><p>We initiate view model router.</p><p>We pass current view controller to router.</p><p><strong>2. <em>Create Router class</em></strong></p><pre>class EmployeeListRouter {</pre><pre>var viewController: UIViewController?</pre><pre>}</pre><p>Create Router class and add view controller parameter. (This view controller help in navigation to next screens)</p><p><strong>3. <em>Create Router Protocol</em></strong></p><pre>protocol EmployeeListRouterProtocol {</pre><pre>func routeToEmployeeDetailScreen(empData: EmployeeData?)</pre><pre>}</pre><p>Create a router protocol and declare navigation methods as part of it.</p><p><strong>4. <em>Extend Router(implement router protocols methods in Router extension)</em></strong></p><pre>extension EmployeeListRouter: EmployeeListRouterProtocol {</pre><pre>func routeToEmployeeDetailScreen(empData: EmployeeData?) {</pre><pre>let empDetail = EmployeeDetailModule().createModule()</pre><pre>empDetail.employeeDetailViewModel.empData = empData</pre><pre>viewController?.navigationController?.pushViewController(empDetail, animated: true)</pre><pre>}</pre><pre>}</pre><p>Implementing Router Protocol Methods in the Router Extension We can pass data to the next screen (using parameter data) at the time of navigation.</p><p><strong>Use of Router example</strong></p><ol><li>Under SceneDelagate, we create the Employee List module and configure rootviewcontroller in NavigationViewController.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mi1SDe6fsnYydIQDWh09LQ.png" /></figure><p>2.In EmployeeListRouter extension we created the Employee Detail module and passed Employee data as part of it to the next screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8iJhOT3kiO6uw7E_aSryg.png" /></figure><h3><strong>Conclusion:</strong></h3><ol><li>We moved routing code to Routing section.</li><li>This makes the code more loosely coupled and better testability. Because your code isn’t dependent on other objects now and they are just passed on, this makes your unit tests easier to write.</li><li>If routing logic changes, you will just edit router, instead of searching for push/present statements in VC.</li></ol><p>Download the code from <a href="https://github.com/LalitKY/MVVMR">here</a>. Please write your thoughts in comments section. I will be happy to answer.</p><p><strong>Happy Coding.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*1SnN5VZ0J4_S2QFUhhbaIA.jpeg" /></figure><blockquote>Thank you so much for reading this article, Please refer to my more series articles as well like <a href="https://medium.com/p/7bd7fa0a3690">Sorting algorithms</a>, <a href="https://medium.com/@lalitkya31/ios-certificate-pinning-part-1-alamofire-e6dc2ba50e12">Certificate Pinning</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84ea115e15c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS: GraphQL apollo client with multi api URL’s]]></title>
            <link>https://medium.com/@lalitkya31/ios-graphql-apollo-client-with-multi-api-urls-d479ebe4d7fb?source=rss-bc770f143f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/d479ebe4d7fb</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[certificate-pinning]]></category>
            <dc:creator><![CDATA[lalit kant]]></dc:creator>
            <pubDate>Thu, 24 Mar 2022 04:08:24 GMT</pubDate>
            <atom:updated>2022-03-24T04:08:24.911Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem</h3><p>As per library shared by <a href="https://www.apollographql.com/docs/ios/tutorial/tutorial-execute-query">Apollo</a> for GraphQL. It’s not clear that <strong>HOW</strong> to make multiple api call from Manager class.</p><p>Why worry?? Here is solution.</p><h3>Solution</h3><p>Steps:</p><ol><li>Define GraphQL api calls Enum.</li><li>Create GraphQL Apollo Client by passing URL string from the GraphQL api calls enum value. (Same can be done for all type of GraphQL call e.g. fetch, subscribe, perform etc.)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*RapkUjb_WJYF2pK9-XfMGg.jpeg" /><figcaption><strong>Its simple like second option</strong></figcaption></figure><p><strong>Implementation</strong></p><p>I created a sample where we need to fetch Film list using GraphQL.</p><ol><li><strong>GraphQLNetworkManager class </strong>has a fucttion <strong>getApollo </strong>with parameter<strong> GraphQLType </strong>which<strong> return ApolloClient </strong>for<strong> multi api URL’s.</strong></li><li>We have a <strong>GraphQLType enum</strong>(String<strong> </strong>type) has cases setup for api’s used for GraphQL.</li><li>We have a function name <strong>getGraphQLURL</strong> in <strong>GraphQLNetworkManager class </strong>which return Api base url based on <strong>GraphQLType enum</strong> passed in method parameter</li></ol><p><strong>Focused Code Snippet Manager class</strong></p><pre>enum GraphQLType: String {</pre><pre>case filmList = &quot;filmList&quot;</pre><pre>case subscription = &quot;Subscription&quot;</pre><pre>}</pre><pre>/// GraphQl network manager</pre><pre>final class GraphQLNetworkManager {</pre><pre>/// set apollo and get apollo client instance</pre><pre>/// - Parameter type: type of GraphLQ api</pre><pre>/// - Returns: ApolloClient</pre><pre>func getApollo(type: GraphQLType) -&gt; ApolloClient {</pre><pre>let sessionConfig = URLSessionConfiguration.default</pre><pre>// MARK: PromiscuousURLSessionClient is for Certificate/SSL pinning</pre><pre>let client = PromiscuousURLSessionClient(sessionConfiguration: sessionConfig )</pre><pre>let cache = InMemoryNormalizedCache()</pre><pre>let store = ApolloStore(cache: cache)</pre><pre>let provider = NetworkInterceptorProvider(store: store, client: client)</pre><pre>let url = URL(string: getGraphQLURL(type: type))!</pre><pre>let transport = RequestChainNetworkTransport(interceptorProvider: provider, endpointURL: url)</pre><pre>let splitNetworkTransport = SplitNetworkTransport(</pre><pre>uploadingNetworkTransport: transport,</pre><pre>webSocketNetworkTransport: self.webSocketTransport</pre><pre>)</pre><pre>return ApolloClient(networkTransport: splitNetworkTransport, store: store)</pre><pre>}</pre><pre>/// getGraphQL URL for specific</pre><pre>/// - Parameter type: type of graphLQ api</pre><pre>/// - Returns: api url</pre><pre>private func getGraphQLURL(type: GraphQLType) -&gt; String {</pre><pre>switch type {</pre><pre>case .filmList:</pre><pre>return &quot;http://localhost:58800&quot;</pre><pre>case .subscription:</pre><pre>return &quot;http://localhost:subscription&quot;</pre><pre>}</pre><pre>}</pre><pre>}</pre><p><strong>How to use? </strong>Here we go…..</p><pre>GraphQLNetworkManager().getApollo(type: .filmList).fetch(query: AllFilmsQuery()) {  result in</pre><pre>switch result {</pre><pre>case .success(let graphQLResult):</pre><pre>debugPrint(graphQLResult)</pre><pre>case .failure(let error):</pre><pre>debugPrint(error)</pre><pre>}</pre><pre>}</pre><p>You can have Download the code snippet from <a href="https://github.com/LalitKY/GraphQL_Multiple_Api_Url">here</a>.</p><p><strong>Happy Coding</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*8gsMpq6Ju-aItREv6xfZ5A.jpeg" /><figcaption><strong>Happy Coding</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d479ebe4d7fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS: Certificate pinning Part — 2 (GraphQL)]]></title>
            <link>https://medium.com/@lalitkya31/ios-certificate-pinning-part-2-graphql-6073af723a26?source=rss-bc770f143f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/6073af723a26</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[ios-application-security]]></category>
            <category><![CDATA[certificate-pinning]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ssl-pinning]]></category>
            <dc:creator><![CDATA[lalit kant]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 04:04:05 GMT</pubDate>
            <atom:updated>2022-03-22T04:04:05.946Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS: Certificate pinning Part — 2 (GraphQL)</h3><p>In <a href="https://medium.com/@lalitkya31/ios-certificate-pinning-part-1-alamofire-e6dc2ba50e12">Part — 1</a> of this session we have gone through basics of Certificate pinning and I have explained about Alamofire in first session. Please go through <a href="https://medium.com/@lalitkya31/ios-certificate-pinning-part-1-alamofire-e6dc2ba50e12">Part-1</a> if you want to implement certificate pinning using Alamofire in iOS.</p><h3>Certificate pinning using <strong>GraphQL</strong>:</h3><p>There are following ways to do Certificate pinning:</p><ol><li>Embedding the Public Key</li><li>Embedding the Certificate</li><li>Embedding the Fingerprint</li></ol><p>In this Session I will show you how to implement certificate pinning with Certificate Fingerprints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*13MNpVVQXw0zqYFBtF_nNA.jpeg" /></figure><h3><strong>Let’s start</strong></h3><p>Download Intermediate and root certificate from your secured api url. I am taking example of <a href="https://stackoverflow.com/">https://stackoverflow.com/</a>.</p><p>Check below image, First certificate is Root and second is intermediate in boxes. The last one is Leaf certificate with least life span. So, we ignore this as of now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1u7LTzlNFHRD1Ehz5SqvA.png" /></figure><p>Goto <a href="https://hash.online-convert.com/sha256-generator">https://hash.online-convert.com/sha256-generator</a> site and upload downloaded certificates and get hex key after processing. Check below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBKgRbbtjm1ndy9xLWs8wA.png" /></figure><p>Keep those keys into you project in some constants.</p><figure><img alt="Lazy work Over, Lets begin the fun part" src="https://cdn-images-1.medium.com/max/1024/1*QYD1-5rJMPwHWqsI6iFKgQ.jpeg" /><figcaption><strong>Lazy work Over, Lets begin the fun part</strong></figcaption></figure><h3>Implementation</h3><p><strong>Simple Steps:</strong></p><ol><li>Create a class <strong>GraphQLNetworkManager</strong></li></ol><p>2. Create function return Apollo client. Check Apollo client implementation from <a href="https://www.apollographql.com/docs/ios/initialization/">https://www.apollographql.com/docs/ios/initialization/</a>. Add Other required methods based on your project need.</p><pre>/// set apollo and get apollo client instance</pre><pre>/// - Parameter type: type of GraphLQ api</pre><pre>/// - Returns: ApolloClient</pre><pre>func getApolloClient() -&gt; ApolloClient {</pre><pre>let sessionConfig = URLSessionConfiguration.default</pre><pre><strong>// MARK: Setting up PromiscuousURLSessionClient help us to do certificate pinning</strong></pre><pre><strong>let client = PromiscuousURLSessionClient(sessionConfiguration: sessionConfig )</strong></pre><pre>let cache = InMemoryNormalizedCache()</pre><pre>let store = ApolloStore(cache: cache)</pre><pre>let provider = NetworkInterceptorProvider(store: store, client: client)</pre><pre>let url = URL(string: &quot;http://localhost:58800&quot;)!</pre><pre>let transport = RequestChainNetworkTransport(interceptorProvider: provider, endpointURL: url)</pre><pre>let splitNetworkTransport = SplitNetworkTransport(</pre><pre>uploadingNetworkTransport: transport,</pre><pre>webSocketNetworkTransport: self.webSocketTransport</pre><pre>)</pre><pre>// self.webSocketTransport is for calling subscription api&#39;s</pre><pre>return ApolloClient(networkTransport: splitNetworkTransport, store: store)</pre><pre>}</pre><p>3. Create a class <strong>PromiscuousURLSessionClient </strong>which inherit <strong>URLSessionClient.</strong></p><p>Basically what it does is it call <strong>URLAuthenticationChallenge</strong> delegate to as soon there is an api hit with GraphQL.</p><pre>override func urlSession( _ session: URLSession,</pre><pre>didReceive challenge: URLAuthenticationChallenge,</pre><pre>completionHandler: @escaping ( URLSession.AuthChallengeDisposition,</pre><pre>URLCredential? ) -&gt; Void )</pre><p>4. Add Below class in your project. Format the code.</p><pre>import Foundation</pre><pre>import Apollo</pre><pre>import ApolloWebSocket</pre><pre>import Security</pre><pre>import CommonCrypto</pre><pre>import UIKit</pre><pre>/// Custom class to do ssl pinning using fingerprints</pre><pre>final class PromiscuousURLSessionClient: URLSessionClient {</pre><pre>override func urlSession( _ session: URLSession,</pre><pre>didReceive challenge: URLAuthenticationChallenge,</pre><pre>completionHandler: @escaping ( URLSession.AuthChallengeDisposition,</pre><pre>URLCredential? ) -&gt; Void ) {</pre><pre>guard let serverTrust = challenge.protectionSpace.serverTrust else {</pre><pre>completionHandler(.cancelAuthenticationChallenge,nil)</pre><pre>return</pre><pre>}</pre><pre>if validate(serverTrust: serverTrust){</pre><pre>let credential = URLCredential(trust: serverTrust)</pre><pre>completionHandler(.useCredential, credential)</pre><pre>} else {</pre><pre>completionHandler(.cancelAuthenticationChallenge, nil)</pre><pre>}</pre><pre>}</pre><pre>/// Validates an object used to evaluate trust&#39;s certificate by comparing their&#39;s fingerprint to the known</pre><pre>/// trused fingerprint stored in the app</pre><pre>/// - Parameter serverTrust: The object used to evaluate trust.</pre><pre>/// - Returns: Validate and compare local fingerprint with server certificate fingerprint</pre><pre>func validate(serverTrust: SecTrust) -&gt; Bool {</pre><pre><strong>let fingerPrints = [&quot;Root certificate fingerprint&quot;,</strong></pre><pre><strong>&quot;Intermediate certificate fingerprint&quot;]</strong></pre><pre>// Check if the trust is valid</pre><pre>let status = SecTrustEvaluateWithError(serverTrust, nil)</pre><pre>guard status else {</pre><pre>return false</pre><pre>}</pre><pre>// For each certificate in the valid trust:</pre><pre>var fingerPrintMatchedCount = 0</pre><pre>if #available(iOS 15, *) {</pre><pre>if let certificates = SecTrustCopyCertificateChain(serverTrust) as? [SecCertificate] {</pre><pre>_ = certificates.map {</pre><pre>let remoteCertData: NSData = SecCertificateCopyData($0)</pre><pre>let fingerprint = (remoteCertData as Data).sha256()</pre><pre>if fingerPrints.contains(fingerprint) {</pre><pre>fingerPrintMatchedCount += 1</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>} else {</pre><pre>for index in 1..&lt;SecTrustGetCertificateCount(serverTrust) {</pre><pre>// Get the public key data for the certificate at the current index of the loop.</pre><pre>guard let certificate = SecTrustGetCertificateAtIndex(serverTrust, index) else {</pre><pre>return false</pre><pre>}</pre><pre>let remoteCertData: NSData = SecCertificateCopyData(certificate)</pre><pre>let fingerprint = (remoteCertData as Data).sha256()</pre><pre>if fingerPrints.contains(fingerprint) {</pre><pre>fingerPrintMatchedCount += 1</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>return fingerPrintMatchedCount &gt;= 2</pre><pre>}</pre><pre>}</pre><p>5. Update certificates fingerprints in following function</p><pre>func validate(serverTrust: SecTrust)</pre><p>6. Add Data extension to return sha256 string.</p><pre>import Foundation</pre><pre>import Security</pre><pre>import CommonCrypto</pre><pre>/// Data extension to return sha256 string</pre><pre>extension Data {</pre><pre>/// returns sha256 string</pre><pre>/// - Returns: Sha256 string</pre><pre>func sha256() -&gt; String {</pre><pre>return hexStringFromData(input: digest(input: self as NSData))</pre><pre>}</pre><pre>/// Returns Data for certificate data digest</pre><pre>/// - Parameter : input intake certificate data</pre><pre>/// - Returns: Sha256 digested with NSdata</pre><pre>private func digest(input : NSData) -&gt; NSData {</pre><pre>let digestLength = Int(CC_SHA256_DIGEST_LENGTH)</pre><pre>var hash = [UInt8](repeating: 0, count: digestLength)</pre><pre>CC_SHA256(input.bytes, UInt32(input.length), &amp;hash)</pre><pre>return NSData(bytes: hash, length: digestLength)</pre><pre>}</pre><pre>/// Returns hash string from data</pre><pre>/// - Parameter : input intake certificate data</pre><pre>/// - Returns: hash string</pre><pre>private func hexStringFromData(input: NSData) -&gt; String {</pre><pre>var bytes = [UInt8](repeating: 0, count: input.length)</pre><pre>input.getBytes(&amp;bytes, length: input.length)</pre><pre>var hexString = &quot;&quot;</pre><pre>for byte in bytes {</pre><pre>hexString += String(format:&quot;%02x&quot;, UInt8(byte))</pre><pre>}</pre><pre>return hexString</pre><pre>}</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*FEls0z-5goKR8eElUgIqiw.jpeg" /><figcaption><strong>Happy Coding.</strong></figcaption></figure><p><strong>Conclusion</strong>: Using Certificate Fingerprints we don’t need to keep certificate in the project directory. So, it will give one more layer of obfuscation to our code. MITM possibility will also get some more limitation. Means when Perpetrator attack in the app he won’t be able to update the certificate. He can only modify the keys in the app by some hack but fingerprints are always compared with api’s fingerprint response. So, MITM possibility will reduce.</p><blockquote><strong>You will find well written and formatted code from </strong><a href="https://github.com/LalitKY/CertificatePinningGraphQL"><strong>Here</strong></a><strong> for Part - 2. Download and proceed.</strong></blockquote><blockquote><strong>If your requirement is to</strong> implement certificate pinning using Alamofire then please Follow Part — 1<strong>.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6073af723a26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS: Certificate pinning Part - 1 (Alamofire)]]></title>
            <link>https://medium.com/@lalitkya31/ios-certificate-pinning-part-1-alamofire-e6dc2ba50e12?source=rss-bc770f143f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6dc2ba50e12</guid>
            <category><![CDATA[alamofire]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[iphone-app-development]]></category>
            <category><![CDATA[certificate-pinning]]></category>
            <category><![CDATA[ssl-pinning]]></category>
            <dc:creator><![CDATA[lalit kant]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 07:25:37 GMT</pubDate>
            <atom:updated>2022-03-21T08:00:00.602Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Certificate Pinning?</h3><p>Certificate pinning is one of the basic security mechanisms of network communication.This technique validates the server certificates again, even after SSL handshaking. The developer embeds a list of trustful certificates inside the client application and compare them with the server certificates during runtime. In case of a mismatch between the server’s certificates and the local copy, the connection is simply aborted.</p><h3>Why Certificate Pinning?</h3><p>Imagine you are using a public Wi-Fi network on the train. That network might be created by someone who wants to read the data sent by you. Since that person is providing your internet connection, they can create their own certificate and tell you to encrypt your data with it. Because this person created the certificate, they can read all the data inside it and then send it further to the right receiver. You may not see that you’re using the wrong certificate. This technique is called a man-in-the-middle attack. This illustration shows how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*vpCHv4PdPQb8ZOBqE8VEew.jpeg" /></figure><h3>How to prevent invalid certificate?</h3><p>This is where certificate pinning and public key pinning come in. These approaches consist of defining a list of valid certificates/public keys. Every time the app sends data, it checks if that certificate is on the list of trusted certificates/public keys. This list of certificates/public keys may be hard-coded or defined in a file. Both solutions prevent man-in-the-middle attacks and should pass a penetration test. If you want to be even more secure, you may also encrypt the certificate to make it harder to get.</p><p>More formal definition:</p><p>“Server/Host is associated with a certificate or public key. You configure the app to reject all certificates other than the predefined certificates or public keys. Whenever the app connects to a server, it compares the server certificate with the pinned certificate(s) or public key(s). If and only if they match, the app trusts the server and establishes the connection.”</p><h3>Implementation</h3><h3>iOS:</h3><ol><li>For Restful api’s we used public kay pinning(Preferred) as we are using Alamofire for rest api’s.</li><li>For GraphQL api’s we used Certificate Pinning Fingerprint as we are using Apollo library for GraphQl.</li></ol><h3>Certificate setup:</h3><p>We initially downloaded Intermediate certificate from a secured website URL, I am taking an example of <a href="https://stackoverflow.com/">https://stackoverflow.com</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jR3jFUyXuO-UbCby7s7mpw.jpeg" /></figure><p>Drag drop certificate icon to your desktop by dragging and drop picking icon in screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*_sSdaG0UiK6KAuhmxgxq1g.png" /></figure><p>Kept in app bundle like below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtO_pR6LanbY1l4a96tUTg.png" /></figure><h3><strong>Alamofire:</strong></h3><blockquote>In Alamofire we need to set Evaluator for hosts means we need to pass a dictionary of host and its ServerTrustEvaluating.</blockquote><p><strong>Public Key Pinning:</strong></p><pre>private var afSession: Session!</pre><pre>func certificatePinningWithAlamofirePublicKey() {</pre><pre>// Build serverTrust manager for public key, Alamofire 5 +  don&#39;t support explicit public key pinning, It extract public key from certificate and compare it with api response public key</pre><pre>let manager = ServerTrustManager(evaluators: NetworkAdapterUtility().buildEvaluators(evaluator_hosts: [&quot;stackoverflow.com&quot;]))</pre><pre>afSession = Session(serverTrustManager: manager)</pre><pre>certificatePinning()</pre><pre>}</pre><p><strong>Pinning with Pinned certificate:</strong></p><pre>private var afSession: Session!</pre><pre>func certificatePinningWithPinnedCertificatesTrustEvaluator() {</pre><pre>let certificates = [</pre><pre>&quot;stackoverflow.com&quot;:</pre><pre>PinnedCertificatesTrustEvaluator(certificates: [Certificates.certificate],</pre><pre>acceptSelfSignedCertificates: false,</pre><pre>performDefaultValidation: true,</pre><pre>validateHost: true)</pre><pre>]</pre><pre>let serverTrustPolicy = ServerTrustManager(</pre><pre>allHostsMustBeEvaluated: true,</pre><pre>evaluators: certificates</pre><pre>)</pre><pre>afSession = Session(serverTrustManager: serverTrustPolicy)</pre><pre>certificatePinning()</pre><pre>}</pre><p>Common Method</p><pre>func certificatePinning() {</pre><pre>afSession</pre><pre>.request(&quot;https://stackoverflow.com/questions/34611112/certificate-pinning-in-alamofire&quot;, method: .get)</pre><pre>.validate()</pre><pre>.response(completionHandler: { response in</pre><pre>switch response.result {</pre><pre>case .success:</pre><pre>print(response.data ?? Data())</pre><pre>case .failure(let error):</pre><pre>switch error {</pre><pre>case .serverTrustEvaluationFailed(let reason):</pre><pre>/* Try Removing stackoverflow.cer file from project folder compiler will execute serverTrustEvaluationFailed case</pre><pre>error: Alamofire.AFError.ServerTrustFailureReason.noPublicKeysFound</pre><pre>Goto ServerTrustFailureReason class implementation you will find all SSL pinning failure cases</pre><pre>*/</pre><pre>// The reason here is a place where you might fine-tune your</pre><pre>// error handling and possibly deduce if it&#39;s an actualy MITM</pre><pre>// or just another error, like certificate issue.</pre><pre>//</pre><pre>// In this case, this will show `noRequiredEvaluator` if you try</pre><pre>// testing against a domain not in the evaluators list which is</pre><pre>// the closest I&#39;m willing to setting up a MITM. In production,</pre><pre>// it will most likely be one of the other evaluation errors.</pre><pre>debugPrint(reason)</pre><pre>default:</pre><pre>debugPrint(error)</pre><pre>}</pre><pre>}</pre><pre>})</pre><pre>}</pre><pre>struct Certificates {</pre><pre>static let certificate: SecCertificate = Certificates.certificate(filename: &quot;stackoverflow&quot;)</pre><pre>private static func certificate(filename: String) -&gt; SecCertificate {</pre><pre>let filePath = Bundle.main.path(forResource: filename, ofType: &quot;cer&quot;)!</pre><pre>let data = try! Data(contentsOf: URL(fileURLWithPath: filePath))</pre><pre>let certificate = SecCertificateCreateWithData(nil, data as CFData)!</pre><pre>return certificate</pre><pre>}</pre><pre>}</pre><p>Try Removing stackoverflow.cer file from project folder <a href="https://github.com/LalitKY/SSLPinningAlamofire">here</a> compiler will execute serverTrustEvaluationFailed case</p><p>error: Alamofire.AFError.ServerTrustFailureReason.noPublicKeysFound</p><p>Goto ServerTrustFailureReason class implementation you will find all SSL pinning failure cases.</p><p><strong>Conclusion</strong>: <em>Certificate Pinning with Alamofire</em> is pretty streight-forward and easy. Nevertheless Alamofire is third party framwork, always keep an eye on Alamofire framework updates. There can be some threat to security, so keep your project updated with latest security guidelines.</p><blockquote>Download complete code from here. Happy Coding..</blockquote><blockquote><a href="https://github.com/LalitKY/SSLPinningAlamofire">https://github.com/LalitKY/SSLPinningAlamofire</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6dc2ba50e12" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>