<?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 Sheeraz Ahmed on Medium]]></title>
        <description><![CDATA[Stories by Sheeraz Ahmed on Medium]]></description>
        <link>https://medium.com/@shirazkhan030?source=rss-75e52d86e771------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CQorKui3EVzZLdOlYWioMA.jpeg</url>
            <title>Stories by Sheeraz Ahmed on Medium</title>
            <link>https://medium.com/@shirazkhan030?source=rss-75e52d86e771------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:29:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shirazkhan030/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[Biometric Authentication With Keychain in iOS]]></title>
            <link>https://shirazkhan030.medium.com/biometric-authentication-in-ios-6c53c54f17df?source=rss-75e52d86e771------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c53c54f17df</guid>
            <category><![CDATA[lacontext]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[apple-login]]></category>
            <category><![CDATA[biometrics]]></category>
            <dc:creator><![CDATA[Sheeraz Ahmed]]></dc:creator>
            <pubDate>Fri, 03 Dec 2021 14:25:39 GMT</pubDate>
            <atom:updated>2021-12-06T07:28:41.114Z</atom:updated>
            <content:encoded><![CDATA[<p>Properly setting up biometric authentication in iOS with Keychain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*3yoQrSBnNLdpaJorfAThJw.png" /></figure><p>Users love Touch ID and Face ID because these authentication mechanisms let them access their devices securely, with minimal effort. Today most Apps provide a biometric authentication system for their users to have secure and easy access to their Apps.</p><p>Let&#39;s discuss how can we properly set up biometrics in our App.</p><h3>Set the Face ID Usage Description</h3><p>In any project that uses biometrics, include the <a href="https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW75">NSFaceIDUsageDescription</a> key in your app’s Info.plist file. Without this key, the system won’t allow your app to use Face ID. The value for this key is a string that the system presents to the user the first time your app attempts to use Face ID. The string should clearly explain why your app needs access to this authentication mechanism. The system doesn’t require a comparable usage description for Touch ID.</p><p>Let&#39;s create a Biometrics Manager class.</p><pre>class BiometricsManager {</pre><pre>static var shared: BiometricsManager = BiometricsManager() </pre><pre>private init() {}</pre><pre>}</pre><h3>Create and Configure a Context</h3><p>You perform biometric authentication in your app using an <a href="https://developer.apple.com/documentation/localauthentication/lacontext">LAContext</a> instance, which brokers interaction between your app and the Secure Enclave. Begin by creating a context inside your Biometrics Manager class with a device Biometrics type to identify if your device supports biometrics and if it does what kind of biometrics does it supports(Touch Id or FaceId)</p><pre>var context = LAContext()</pre><pre>var error: NSError?</pre><pre>lazy var biometricType: LABiometryType? = {</pre><pre>func checkForBiometricsPermission(completion: @escaping((Bool) -&gt; Void)) {</pre><pre>context.localizedCancelTitle = &quot;Enter Username/Password&quot;</pre><pre>var error: NSError?</pre><pre>let permission =  context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &amp;error)</pre><pre>permission ? completion(true) : completion(false)</pre><pre>}</pre><p>You can always return a localized text in the evaluatePolicy parameter based on your requirement and design type like this. We will use this method below when we ask the user for his biometric permission.</p><pre>var authenticationTypeReason: String {</pre><pre>switch biometricType {</pre><pre>case .faceID:</pre><pre>return &quot;Log in with Face ID&quot;</pre><pre>case .touchID:</pre><pre>return &quot;Log in with Touch ID&quot;</pre><pre>case .none:</pre><pre>return &quot;&quot;</pre><pre>@unknown default:</pre><pre>return &quot;&quot;</pre><pre>}</pre><pre>}</pre><p>Choose a value from the <a href="https://developer.apple.com/documentation/localauthentication/lapolicy">LAPolicy</a> enumeration for which to test. The policy controls how the authentication behaves. For example, the <a href="https://developer.apple.com/documentation/localauthentication/lapolicy/deviceownerauthentication">LAPolicy.deviceOwnerAuthentication</a> policy used in this sample indicates that reverting to a passcode is allowed when biometrics fails or is unavailable. Alternatively, you can indicate the <a href="https://developer.apple.com/documentation/localauthentication/lapolicy/deviceownerauthenticationwithbiometrics">LAPolicy.deviceOwnerAuthenticationWithBiometrics</a> policy, which doesn’t allow reverting to the device passcode. We will use deviceOwnerAuthentication so we can have a fallback to passcode if biometric fails.</p><p>Now we can check if the device has biometrics and if yes we can ask user for the biometrics permission.</p><pre>// .deviceOwnerAuthentication allows biometric or passcode authentication</pre><pre>func authenticateWithBiometrics(completion: @escaping((Bool, String?) -&gt; Void)) {</pre><pre>checkForBiometricsPermission { permission in</pre><pre>if permission {</pre><pre>context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: authenticationTypeReason) { success, error in</pre><pre>if success, error == nil {</pre><pre>// Handle successful authentication</pre><pre>completion(true, nil)</pre><pre>} else {</pre><pre>// Handle LAError error</pre><pre>if let err = error {</pre><pre>completion(false, self.getErrorDetails(error: err as NSError))</pre><pre>}</pre><pre>else {</pre><pre>completion(false, nil)</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>else {</pre><pre>completion(false, nil)</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Apple returns LAError for the error code we provided based on our Biometrics authentication failure. In this method I am returning the comments written for each of the error codes by Apple as string, you can do whatever you need based on your requirement.</p><pre>private func getErrorDetails(error: NSError) -&gt; String {</pre><pre>// If error is an instance of LAError</pre><pre>if let code = LAError.Code(rawValue: error.code) {</pre><pre>switch code {</pre><pre>case .appCancel:</pre><pre>return &quot;Authentication was canceled by application.&quot;</pre><pre>case .authenticationFailed:</pre><pre>return &quot;Authentication was not successful because user failed to provide valid credentials.&quot;</pre><pre>case .invalidContext:</pre><pre>return &quot;The LAContext was invalid&quot;</pre><pre>case .notInteractive:</pre><pre>return &quot;Authentication failed because it would require showing UI which has been forbidden&quot;</pre><pre>case .passcodeNotSet:</pre><pre>return &quot;Authentication could not start because passcode is not set on the device&quot;</pre><pre>case LAError.Code.systemCancel:</pre><pre>return &quot;Authentication was canceled by system (e.g. another application went to foreground)&quot;</pre><pre>case LAError.Code.userCancel:</pre><pre>return &quot;Authentication was canceled by user (e.g. tapped Cancel button).&quot;</pre><pre>case LAError.Code.userFallback:</pre><pre>return &quot;Authentication was canceled because the user tapped the fallback button (Enter Password).&quot;</pre><pre>case LAError.Code.biometryLockout:</pre><pre>return &quot;Authentication was not successful because there were too many failed Touch ID attempts and Touch ID is now locked. Passcode is required to unlock Touch ID&quot;</pre><pre>case LAError.Code.biometryNotAvailable:</pre><pre>return &quot;Authentication could not start because Touch ID is not available on the device.&quot;</pre><pre>case LAError.Code.biometryNotEnrolled:</pre><pre>return &quot;Authentication could not start because Touch ID has no enrolled fingers.&quot;</pre><pre>case .touchIDNotAvailable:</pre><pre>return &quot;Authentication could not start because Touch ID is not available on the device.&quot;</pre><pre>case .touchIDNotEnrolled:</pre><pre>return &quot;Authentication could not start because Touch ID has no enrolled fingers.&quot;</pre><pre>case .touchIDLockout:</pre><pre>return &quot;Authentication was not successful because there were too many failed Touch ID attempts and Touch ID is now locked. Passcode is required to unlock Touch ID&quot;</pre><pre>@unknown default:</pre><pre>return &quot;Unknown Error Occurred&quot;</pre><pre>}</pre><pre>}</pre><pre>return &quot;Unknown Error Occurred&quot;</pre><pre>}</pre><p>Now let&#39;s set up Keychain.<br>We will be using KeychainWrapper dependency so that we don&#39;t have to code for keychain setup all from scratch. <strong><em>KeychainWrapper</em></strong> is an excellent pod that provides flexibility to use Keychain as similar to UserDefaults, also been recommended by Paul Hudson. <br>Below is the link to the Pod. You can either install it using cocoapods or SMP.</p><p><a href="https://github.com/jrendel/SwiftKeychainWrapper">https://github.com/jrendel/SwiftKeychainWrapper</a></p><p>Let&#39;s create our Keychain Storage class so we can store user credentials in the Keychain by converting them into Data(), once we receive authentication information from the user the first time. Next time he can log in with biometrics, based on if the credentials are already stored in the keychain and his biometrics matches the device biometrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leUcqhEZb9W8gaK1fggZng.png" /><figcaption>This is what apple says about secure entry storage.</figcaption></figure><p>First, we will create a model class to hold the credentials, and then we can save and return them from our KeychainStroage class.</p><pre>struct Credentials: Codable {</pre><pre>var email: String?</pre><pre>var password: String?</pre><pre>func encode() -&gt; String {</pre><pre>let encoder = JSONEncoder()</pre><pre>if let credentials = try? encoder.encode(self) {</pre><pre>return String(data: credentials, encoding: .utf8) ?? &quot;&quot;</pre><pre>}</pre><pre>return &quot;&quot;</pre><pre>}</pre><pre>static func decode(credentials: String) -&gt; Credentials? {</pre><pre>let decoder = JSONDecoder()</pre><pre>guard let jsonData = credentials.data(using: .utf8) else { return nil }</pre><pre>guard let credentials = try? decoder.decode(Credentials.self, from: jsonData) else { return nil }</pre><pre>return credentials</pre><pre>}</pre><pre>}</pre><p>Now let&#39;s create two methods to set and get our credentials in our keychain.</p><pre>struct KeyChainStorage {</pre><pre>static var key = &quot;credentials&quot;</pre><pre>static func getCredentials() -&gt; Credentials? {</pre><pre>if let credentials = KeychainWrapper.standard.string(forKey: key) {</pre><pre>return Credentials.decode(credentials: credentials)</pre><pre>}</pre><pre>return nil</pre><pre>}</pre><pre>static func saveCredentials(credentials: Credentials) {</pre><pre>KeychainWrapper.standard.set(credentials.encode(), forKey: key)</pre><pre>}</pre><pre>}</pre><p>Our work is done, now we can do the implementation.<br>First of all, we will need to save the credentials in the keychain whenever a user logs in. <br>I will not implement a full API call but let&#39;s assume we have a login API call that takes username and password. So in the success of that API call we can save our credentials in the keychain like this.</p><pre>let creds = Credentials.init(email: userEmail, password: userPassword)</pre><pre>KeyChainStorage.saveCredentials(credentials: creds)</pre><p>Now when calling to authenticate a user through biometrics always remember to do it in the main thread if you are updating any UI component. Like this.</p><pre>DispatchQueue.main.async {</pre><pre>BiometricsManager.shared.authenticateWithBiometrics {[weak self] result, message in</pre><pre>if result, message == nil {</pre><pre>let creds = KeyChainStorage.getCredentials()</pre><pre>self?.callLogin(userEmail: creds?.email ?? &quot;&quot;, userPassword: creds?.password ?? &quot;&quot;)</pre><pre>}</pre><pre>else {</pre><pre>self?.setupMessageDialog(message: message ?? &quot;&quot;)</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>After the login API success completion is called from the credentials we passed from our keychain on successful biometrics, route the user into the App.</p><p>You can check the full code here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd4cf3146255800941a2c5b23c10a2a5/href">https://medium.com/media/dd4cf3146255800941a2c5b23c10a2a5/href</a></iframe><p><strong><em>So that’s basically it!!<br></em></strong>Please leave a comment if you like the article or have any questions in any regard related to the article.<br>Until next time.</p><p>Thank you.<br><a href="http://shirazkhan030/">Sheeraz Ahmed</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c53c54f17df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working on a Software Application having Millions of Users.]]></title>
            <link>https://medium.com/geekculture/working-on-a-software-application-having-millions-of-users-813abd2d656c?source=rss-75e52d86e771------2</link>
            <guid isPermaLink="false">https://medium.com/p/813abd2d656c</guid>
            <category><![CDATA[development-company]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech-startups]]></category>
            <category><![CDATA[fortune-500-companies]]></category>
            <dc:creator><![CDATA[Sheeraz Ahmed]]></dc:creator>
            <pubDate>Tue, 06 Jul 2021 10:02:57 GMT</pubDate>
            <atom:updated>2021-07-06T10:02:57.057Z</atom:updated>
            <content:encoded><![CDATA[<p>Working as an iOS engineer on an application having more than a 10 Million plus user base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mE0zZ-CQ7PG5wJaoIjvN-A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Austin Distel</a> on <a href="https://unsplash.com/s/photos/software-development?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As we all know we work in a very diverse industry, where the criteria of development are different for every organization. Every organization follows its own handbook and its choice of SDLC to develop and move forward with any particular software product.</p><p>In this article, I will share my experience with the development team I work in &amp; will break down how a high-potential product delivers high-quality features to the product team and finally into production.</p><p>Working on a software product with a high user engagement has been very different for me than working on a lower consumer base.<br>It’s been around 1 year I started working on an Application having more than<br>10M+ user-base as an iOS Engineer. Usually, there are multiple development teams for a big product as also in my case.</p><p><strong>Product &amp; Sprint Planning:<br></strong>Usually, the product team is always ahead of the development team with new features &amp; requirements, if the development team is working on sprint no 1, the product team usually has already decided on additional features that would cover up the next 5–10 sprints or even more than that.<br>Based on the development team&#39;s capacity, the Team Manager will pick up the features to be included in the Sprint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdBSLj_eYiPoSiZC96uHmw.png" /><figcaption>An overview of how knowledge is transferred from the product team to managers and then to the technical team.</figcaption></figure><p><strong>Development:<br></strong>After the sprint is locked and sprint understanding has been transferred to the particular feature team, development is started.</p><p>We as software engineers play the most important role in converting raw requirements into highly usable features that goes out as a final product for the end-user.</p><p>Development always requires a clear understanding of the features that are part of the Sprint. <br>Product knowledge plays an essential part in the phase of development for the developer, the more developer knows about the scope of the product and has more technical knowledge of it, there is always higher the chance of delivering a great feature.</p><p>With products of this scale, you usually have to be very alert while writing code, because usually, your code interacts with a lot of old &amp; pre-existing features that can always have a high chance of breaking in production.</p><p>So you always have to run your feature multiple times to make sure everything else is working fine and tests always pass.<br>Nevertheless, you become habitual of it doing it every day.</p><p>Every feature has a priority and a delivery date to go into QA, based on that every developer knows what&#39;s on the priority list.</p><p>After a particular feature is built, both the development teams from different platforms owning that particular feature test it closely before giving it to the internal QA team. The chances of bugs already go down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hm0ra0w2qvRqaKGa7SXQg.png" /><figcaption>Overview of how the development team works for the product.</figcaption></figure><p><strong>Testers:<br></strong>As soon as development is started the QA team, on the other hand, starts writing test cases for the sprint, which effectively helps them to save time and they can easily execute the test cases when any feature comes under testing by the development team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZNd6-x-y7voFzYbbawcsA.png" /><figcaption>Feature testing by the QA Team.</figcaption></figure><p><strong>Fixing Issues:<br></strong>Issues coming from the specific features are usually assigned to the feature owner(developer) as he has better knowledge of it.</p><p>The developer fixes it quickly and it again goes into QA and usually after confirmation the feature is cleared by the QA.</p><p>The cycle continues, this process is applied to every feature until the whole sprint is cleared by the QA making sure the Quality of every feature is at its best.</p><p><strong>Priority Fix:<br></strong>Sometimes you are assigned an issue that was written years ago and it&#39;s now on Priority, in these conditions you can never just go in and change the code assuming it will work fine, sometimes your small fix can cause a lot of trouble. So it&#39;s always best to run that code multiple times concerning how unit tests were written.</p><p><strong>UAT Team:<br></strong>As the Managers, the development, and the QA team make sure that everything is covered, we then send the complete features that were covered in the sprint to the UAT team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OK3VRTo8TEENMst_9kPMzQ.png" /><figcaption>After the sprint is internally tested, the development team provides all the features to the UAT team to test before being sent to the production and production team.</figcaption></figure><p><strong>Sign Off:<br></strong>If everything is fine for the product team they sign off the sprint and after that, the process of the feature going into production starts.<br>And then other teams take over the particular feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dds_hRSHmx9SLhCckJ7Rkw.png" /><figcaption>After UAT assures everything is fine as per their regard they give a sign-off for the sprint.</figcaption></figure><p><strong>Hyper-Care<br></strong>It’s the period of time immediately following a system Go Live where an elevated level of support is available to ensure the seamless adoption of a new system.</p><p>After the launch of a new module, feature, or a whole new app the software teams go into hypercar by providing extra support to their users. This additional support helps new and existing customers understand how to use the newly released feature or module.</p><p><strong><em>So that’s basically it!!<br></em></strong>Just an overview of how great teams always put in a lot of effort for the users to give them a high-quality product. Usually there</p><p>Please leave a comment if you like the article or have any questions in any regard related to the article. <br>Until next time.</p><p>Thank you.<br><a href="http://shirazkhan030/">Sheeraz Ahmed</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=813abd2d656c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/working-on-a-software-application-having-millions-of-users-813abd2d656c">Working on a Software Application having Millions of Users.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Actors in Swift.]]></title>
            <link>https://shirazkhan030.medium.com/introduction-to-actors-in-swift-93c7bb9ec1b7?source=rss-75e52d86e771------2</link>
            <guid isPermaLink="false">https://medium.com/p/93c7bb9ec1b7</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[wwdc-2021]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sheeraz Ahmed]]></dc:creator>
            <pubDate>Sun, 27 Jun 2021 14:03:30 GMT</pubDate>
            <atom:updated>2021-06-28T16:51:05.597Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will discuss the newly released Actors in swift 5.5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BeDIS5zTArXlOapt2Rqcqg.png" /></figure><p>Concurrency is a major part of any Mobile Development Platform, we use concurrent tasks at almost every stage in our Application life Cycle. For example, updating a UI after we have received a response from our API or updating a model after any specif task is completed, etc.</p><p>Talking of concurrencies from a developer point of view, Queues are to be mentioned. Queues are closures that work on different and appropriate threads according to their orders. <br> Queues follow (FIFO) if deployed on multiple threads following concurrency.</p><p>Let&#39;s talk about the type of Queues we have.<br>Queues can be specified into two basic types.</p><p><strong>Type of Queues:</strong></p><ol><li>Serial Queue: Serial queues work in order. It pulls out the first task from the queue, starts working on it, operates on it until it has completed its execution, and then only picks up the new task.</li><li>Concurrent Queue: Like Serial queues, it also pulls up the first task from the queue and initiates its execution in any thread that is available.<br>If the system sees that it has access to more threads, it will pull out other tasks from the queue and initiate them on another thread without waiting for the first execution to be completed. Similarly, it works on any available number of tasks in a queue.</li></ol><p><strong>Concurrent Methods:</strong></p><p>There are two types of methods available when working with queues</p><ol><li>Sync: Returns the control to the current queue after the whole execution of a particular task is completed blocking the whole queue.</li><li>Async: Returns the control to the current queue immediately after initiating a particular task without waiting for it to end, thus it never blocks the whole queue.</li></ol><p>So now we have generally talked about Concurrency. Let&#39;s assume we have a shared reference working under concurrent tasks like updating a string array. <br> Let&#39;s look at an example of doing it the conventional way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnH4GO2MfpaScvIh1mIodA.png" /></figure><p>In this example, we can see that the shared string array is being shared by multiple threads trying to update it. <br>We have no guarantee of which thread will finish fetching first and fall into the completion block. <br>Let&#39;s say our second task gets completed first and after its completion, we are trying to remove an element from 1st position and currently we have no element in the first position, so we can expect a crash here. <br>Or if we are performing another task we can have a race condition.</p><p><strong><em>Data race makes concurrency Hard. It occurs when we have multiple threads accessing/modifying the same data.</em></strong></p><p>We can avoid Data Races using value Types like structs for example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rCzHvPaCviBpG4yOi5wKA.png" /></figure><p>Although now our code is safe but the behavior is not correct.</p><p>This is where Actors come in.<br>Let&#39;s discuss some main features of Actors before we run on a code example.</p><h3><strong>ACTORS:</strong></h3><p>Conceptually similar to classes. Safe to use in concurrent environments because Swift ensures that a mutable state inside your actor is only ever accessed by a single thread at any given time, which helps eliminate a variety of serious bugs right at the compiler level.</p><ol><li>Actors are created using the new <strong>actor</strong> keyword. This is a new concrete nominal type in Swift, joining structs, classes, and enums.</li><li>Actors are reference types.</li><li>Actor isolates data.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZShJedP4Op44fHCi2d817g.png" /></figure><p>Let&#39;s take an example of a class for executing concurrent code. This code will run absolutely fine in a single-threaded environment, but if this code is executed in a multi-threaded environment we will have a race condition.</p><p>Let&#39;s assume in a multi-threaded environment two threads execute <strong>manageEmployeeSalary </strong>method at the same time. Both our threads will transfer the salary to the same employee.</p><p><em>That’s definitely beneficial for the employee but not for the company.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lviPzqUbvufJEx54Pqkxvw.jpeg" /></figure><p>Let&#39;s consider this through Actors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdD_o7nK6Qs0c3XIVFV22g.png" /></figure><p>What is happening here is another admin from outside of the actor is trying to do some modification in our first admin’s business.<br>Our compiler straight away gives an error “Hey you can not do this outside the actor unless you wait for the current task to be finished and then you can do it.” <br>So now we know we can not have race conditions because our compiler does not allow multiple threads to access a single resource at a single time. <br><strong>How cool is that?</strong></p><p>So how can we solve this problem??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*53W7CaxcFBgnwSahCxcZNw.gif" /></figure><p>Well, we have to wait using await keyword for one particular salary transfer to be completed, and then only we can transfer salary to any other employee. <br>We make sure salary is transferred and based on the result we remove the employee from our employee list. <br>This way we will never transfer the salary twice to a single employee.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aG_bMxPD8pdLTEY-Pg9mGA.png" /></figure><p>So now our shared resource <em>employee</em> can never be modified in different threads at a time.</p><p><strong>actors make sure that they are only modified once at a time.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*HNhyM_sn8e-jStAptPVAwA.gif" /><figcaption><em>Sorry employees no more good days.</em></figcaption></figure><p>There are several things to notice in this example.</p><ol><li>Actors are created using the new “actor” keyword</li><li>The <strong>manageEmployeeSalary</strong> method is marked with <strong>async</strong>, because it will need to suspend its work while waiting for the transfer to complete.</li><li>Although the <strong>transferSalaryToEmployee</strong> method is <em>not</em> marked with <strong>async</strong>, we still need to call it <strong>await</strong> because it will wait until anotherAdmin actor is able to handle the request.</li></ol><p>Actor &amp; classes both are reference types, but actors are safe shared states, unlike classes. Both of them share every aspect of each other except classes can be inherited.</p><p>@MainActor is the new keyword that makes sure that your code runs on the main thread. Also, we can do it this way if we want to make sure that we save our data on the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NKDOv3R_Rh3PHu1p5f06A.png" /></figure><p>I guess we now have a basic idea of how actors work and when they can be used. That&#39;s it for this article now.<br>Please let me know if you have any questions!</p><p>Happy Coding!<br><a href="https://shirazkhan030.medium.com/">Sheeraz Ahmed</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93c7bb9ec1b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create and Publish your own Swift Package.]]></title>
            <link>https://shirazkhan030.medium.com/creating-and-publishing-your-own-swift-package-655a4b3ce39f?source=rss-75e52d86e771------2</link>
            <guid isPermaLink="false">https://medium.com/p/655a4b3ce39f</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[love]]></category>
            <category><![CDATA[swift-package-manager]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sheeraz Ahmed]]></dc:creator>
            <pubDate>Fri, 25 Jun 2021 19:52:48 GMT</pubDate>
            <atom:updated>2021-06-28T00:30:53.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qYVtXKjixgDRrqJM63HrZQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@brandablebox?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brandable Box</a> on <a href="https://unsplash.com/s/photos/box?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Swift Package Manager also known as SPM has been around for quite a while now. It&#39;s a really cool feature by Apple allowing us to manage, add and create dependency in a very efficient manner.</p><p>SPM is integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies. We already have popular Package Managers like Cocoa Pods, and Carthage but in this article, we will learn how cool SPM is.</p><p>Let’s say you are working in a team and your team wants a separate private framework that contains the main feature of the app. <br>So instead of managing the classes/code inside the app every time and doing back and forth, you can separately create a dependency/framework that just needs to import and you are good to roll. <br>You can also create a separate public dependency for the community to share cool stuff with them as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YamLeKiaRbbDkG20gMd4ug.jpeg" /></figure><p><strong>Without further ado, let’s dive right In !! :D</strong></p><p>First of all, we need to create an Xcode Project. After you have created an Xcode Project let&#39;s add a new Swift Package Manager to our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrbX-HujPFtqWdM889DzGA.png" /></figure><p>After you have added a new Swift Package to your project you will have these files now. Now let&#39;s get an overview of the files now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*zXbGLuLTWJZz0nRGvYzQJg.png" /></figure><ol><li>ReadMe.md: Here is where you document your Package.</li><li>Package.swift contains all the configurations for your Package. Like external dependencies, your targets, etc. <br>We are not going to add any external dependency to our Package so we can move ahead right now.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJxtG6ZlEXIshjdvUCTUpA.png" /><figcaption>This is your Package.swift file.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8T-i_wuWh-8tjN78104HA.png" /><figcaption>We have to make sure our folder under the sources folder and target name is the same. Here it’s APIManagerPackage!</figcaption></figure><p>Now time to add your code in the ApiManagerPacakge file, in your case you can have a different name file. <br>If you are following along you can use a similar code. So our APIManager is ready. Now next step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d759baa32dcc6917e41beb8cbbe27fb9/href">https://medium.com/media/d759baa32dcc6917e41beb8cbbe27fb9/href</a></iframe><p>Now go to Targets -&gt; General -&gt; Framework Libraries and embedded content and tap on the + button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8tIPZC_F_qDjdGwNmjnhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*J5hdJCLs1R0W-aGA53D_9w.png" /><figcaption>This is our <strong>New Package. </strong>Add it :D</figcaption></figure><p>We have finished creating our Package, lets check if it works fine.</p><p>Go to any class and try to import <strong>APIManagerPackage.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*jyC1Voy8kwrsRF9Bul95rw.png" /></figure><p>Now you can use our Custom created Package in your codebase. Just like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RwyAgwh7yyYnN21CvyPtw.png" /></figure><p>As this said let&#39;s publish our Package. <br>For publishing, the first step you need to do is to copy your Package Manager in any other directory so we can open it separately.<br>I copied mine to the desktop. You can copy wherever you like. <br>Open your SPM using Xcode. This is how it will look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYBkYRwWeyXJDG-Lm2lAwA.png" /></figure><p>Now go to the Source control and click New git Repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrREFYY75kBY5GIn5rTxaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRIRTjy0HHhROq502u9zhw.png" /></figure><p>You will get this window, make sure your checkmark is selected and press create. <br>After that go to the left bottom of your Xcode and you will see a settings icon. Select New “APIManagerPackage” Remote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TO6Gx1KZTGwUiI94n_53Rg.png" /></figure><p>As soon as you tap you will get this information window. In my case, I have my GitHub repo settings here. <br>You can link an account to your Xcode as well from Xcode-&gt;Preferences -&gt; Accounts. <br>So now we can create a remote for our Package in my case I will do a public repo as I will continue working on it ;)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80waw7mLVHbzI0LVY0G2HQ.png" /></figure><p>After you have created a new Repository, you will have to add a tag to your branch like this. You can study more about how to tag your branches in wwdc 2019 session on SPM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*qDAEuYvcEqfTUdr5UzKNiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIdFLc3jsR3gn0cHC_r-uQ.png" /></figure><p>So now our local repo is created branch tags are set up, now to our one final step. <br>Pushing our code to GitHub :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*pQRvhxzSuDaBOFCTg4U8hw.png" /></figure><p>As soon as you select Push your Package should be pushed and should be available on GitHub!</p><p>Let&#39;s check it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*loKZUWlX0i1SZATEM2kqng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xk7gLybYc8JIO81iyic_xg.png" /></figure><p><a href="https://github.com/shazy112/APIManagerPackage">shazy112/APIManagerPackage</a></p><p>Our Package is live :D!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*mVn0lV5a4fX2-4_B3pGXnA.png" /></figure><p>Now lets check if we can add this Swift Package to our Projects actually?!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RGLIgzG9B91c7htmsuCdQ.png" /></figure><p>Paste URL in the URL section and you will be able to see your new Package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jreg7TI7Wgxu_MtJySs1Hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5AB7TcXJ_a3GuakGCZ_mg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90PXWkJSsCASTdb792BYFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*JUtAGVB0QQv7c5_oCVJVqw.png" /></figure><p>And here is we have added our new Package Manager from our Github!!</p><p>That&#39;s it for this article, I hope it will help you guys. Please let me know if you guys have any questions. Thanks!</p><p>Happy Coding.</p><p>Sheeraz Ahmed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=655a4b3ce39f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using URL Sessions with Swift 5.5 Async/await & Codable]]></title>
            <link>https://shirazkhan030.medium.com/using-url-sessions-with-swift-5-5-aysnc-await-codable-8935fe55fbfc?source=rss-75e52d86e771------2</link>
            <guid isPermaLink="false">https://medium.com/p/8935fe55fbfc</guid>
            <category><![CDATA[ios15]]></category>
            <category><![CDATA[api-manager]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swiftfivefive]]></category>
            <dc:creator><![CDATA[Sheeraz Ahmed]]></dc:creator>
            <pubDate>Thu, 24 Jun 2021 10:59:27 GMT</pubDate>
            <atom:updated>2021-06-29T00:36:30.145Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating an API manager with URL Session that will support async/await.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoN0YxCnWdvMs35FaP5tNA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@zanilic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Zan</a> on <a href="https://unsplash.com/s/photos/macbook-xcode?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As we all are familiar that in WWDC-21 apple has introduced asynchronous (async) functions into Swift, allowing us to run complex asynchronous code almost as if it were synchronous. That being said we now don&#39;t have to write complex callback completion handlers or manage delegates for our result as async/await will take care of it. <br>As of now it&#39;s only introduced for iOS 15 and above, but I am sure Apple must be considering giving its support to lower iOS versions as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UeGILHZZAslBdZJq0mjy3w.png" /></figure><p>This is a visual representation of code from WWDC session <a href="https://developer.apple.com/videos/play/wwdc2021/10132/">https://developer.apple.com/videos/play/wwdc2021/10132/</a> where they distinguished between the syntax and complexity difference between completion handlers and aysnc/await using fetch thumbnail as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MC4AbtuOGNifjmD3mGH4Q.png" /><figcaption>Cleaner code with async/await.</figcaption></figure><p>Let’s now dive into our main topic.</p><p>We already know there are huge networking libraries available out there like Alamofire, AFNetworking and Moya but here we are creating very simple methods without any dependency to support our networking calls with URL Sessions.</p><p>Let&#39;s first create all the needful that we will be needing while creating our API Manager.</p><p>Create an enum to state the type of request we will initiate.</p><pre>enum RequestType: String {</pre><pre>case postRequest = &quot;POST&quot;</pre><pre>case getRequest = &quot;GET&quot;</pre><pre>}</pre><p>Create an enum of String type that will contain all our endpoints.</p><pre>enum Endpoint: String {</pre><pre>case getProducts = &quot;get/products&quot;</pre><pre>}</pre><p>Creating a Class For our Api Manager with properties that would be useful.</p><pre>class ApiManager {</pre><pre>var baseURL = &quot;https://api.spoonacular.com/&quot;</pre><pre>static var shared = ApiManager()</pre><pre>private var request: URLRequest?</pre><pre>private init () {} </pre><pre>}</pre><p>Now let&#39;s create all the helper methods that will support our get/post calls and can be customizable according to everyone’s need.</p><p>For GET API calls in which we need to send parameters as URL components. We can write a method that will append all the parameters into URL and then we can create a URL request that we can send to our URLSession.</p><pre>private func createGetRequestWithURLComponents(url:URL,</pre><pre>parameters: [String:Any],</pre><pre>requestType: RequestType) -&gt; URLRequest? {</pre><pre>var components = URLComponents(string: url.absoluteString)!</pre><pre>components.queryItems = parameters.map { (key, value) in</pre><pre>URLQueryItem(name: key, value: &quot;\(value)&quot;)</pre><pre>}</pre><pre>components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: &quot;+&quot;, with: &quot;%2B&quot;)</pre><pre>request = URLRequest(url: components.url ?? url)</pre><pre>request?.httpMethod = requestType.rawValue</pre><pre>return request</pre><pre>}</pre><p>For our POST request, we would need to create a URL request and a httpBody that we need to send to our API.</p><pre>private func createPostRequestWithBody(url:URL, parameters: [String:Any], requestType: RequestType) -&gt; URLRequest? {</pre><pre>request = URLRequest(url: url)</pre><pre>request?.httpMethod = requestType.rawValue</pre><pre>request?.addValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)</pre><pre>request?.addValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Accept&quot;)</pre><pre>if let requestBody = getParameterBody(with: parameters) {</pre><pre>request?.httpBody = requestBody</pre><pre>}</pre><pre>request?.httpMethod = requestType.rawValue</pre><pre>return request</pre><pre>}</pre><p>This method converts our parameters Dictionary into data that we need to assign to httpBody.</p><pre>private func getParameterBody(with parameters: [String:Any]) -&gt; Data? {</pre><pre>guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {</pre><pre>return nil</pre><pre>}</pre><pre>return httpBody</pre><pre>}</pre><p>Creating a method to distinguish between our get/post requests and behave accordingly.</p><pre>private func createRequest(with url: URL, requestType: RequestType, parameters: [String: Any]) -&gt; URLRequest? {</pre><pre>if requestType == .getRequest {</pre><pre>return createGetRequestWithURLComponents(url: url,</pre><pre>parameters: parameters,</pre><pre>requestType: requestType)</pre><pre>}</pre><pre>else {</pre><pre>return createPostRequestWithBody(url: url,</pre><pre>parameters: parameters,</pre><pre>requestType: requestType)</pre><pre>}</pre><pre>}</pre><p><em>Now finally the interesting Part!!! :D</em><strong><em><br></em>Make sure you are using Codable protocol in your models.</strong></p><p>We will have a single method that will be called whenever we make an API request and this method will take care of everything. We have used generics to cast our Codable models directly so we don&#39;t have to create methods separately to cast every particular Model.</p><pre>func sendRequest&lt;T:Codable&gt;(model: T.Type,</pre><pre>with endpoint: Endpoint,</pre><pre>requestType: RequestType,</pre><pre>parameters: [String:Any]) async -&gt; Result&lt;T, Error&gt;? {</pre><pre>if #available(iOS 15.0, *) {</pre><pre>do {</pre><pre>let url = URL(string: baseURL+endpoint.rawValue)!</pre><pre>guard let urlRequest = createRequest(with: url,</pre><pre>requestType: requestType,</pre><pre>parameters: parameters) else {</pre><pre>return nil</pre><pre>}</pre><pre>let (data, _) = try await URLSession.shared.data(for: urlRequest)</pre><pre>let parsedData = try JSONDecoder().decode(model.self, from: data)</pre><pre>return .success(parsedData)</pre><pre>}</pre><pre>catch {</pre><pre>return .failure(error)</pre><pre>}</pre><pre>}</pre><pre>return nil</pre><pre>}</pre><p><strong>Three things to notice:</strong></p><ol><li>We have marked our method with async, as we use await inside our method. An aysnc function can be suspended and can hand over the control of the thread in a very unique way.</li><li>We have used await keyword that tells the compiler to suspend the control of the function and hands over the control to the system rather than giving control back to our function and the system decides which task is more important. Cool Right? !!</li><li>For using async functions we always need to mark our function that we call them in as async as well.</li></ol><p>Now add all our code in to ApiManager class to use it. ;)</p><p>Let&#39;s create a demo Model with Codable protocol</p><pre>struct MyModel: Codable {</pre><pre>var id: String?</pre><pre>var description: String?</pre><pre>}</pre><p>Now just call it like this in any of your method!</p><pre>class YourClass {</pre><pre>func sendApiCall() async {</pre><pre>guard let result = await ApiManager.shared.sendRequest(model: MyModel.self, with: .getProducts, requestType: .postRequest, parameters: [&quot;&quot;:&quot;&quot;]) else {</pre><pre>return</pre><pre>}</pre><pre>switch result {</pre><pre>case .success(let mymodel):</pre><pre>print(mymodel)</pre><pre>case .failure(let error):</pre><pre>print(error.localizedDescription)</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>That’s it for now, please let me know if you guys have any questions.</p><p>Thank you!<br>Happy Coding.</p><p><a href="https://medium.com/@shirazkhan030">Shiraz Khan</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8935fe55fbfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>