<?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 Ali Akhtar on Medium]]></title>
        <description><![CDATA[Stories by Ali Akhtar on Medium]]></description>
        <link>https://medium.com/@ali-akhtar?source=rss-ec9cefb72e16------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UJqG2W7r365v43pb.</url>
            <title>Stories by Ali Akhtar on Medium</title>
            <link>https://medium.com/@ali-akhtar?source=rss-ec9cefb72e16------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 05:49:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ali-akhtar/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[Swift New Concurrency Framework (Part 4) Task]]></title>
            <link>https://ali-akhtar.medium.com/swift-new-concurrency-framework-part-4-task-4a691120eee2?source=rss-ec9cefb72e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a691120eee2</guid>
            <category><![CDATA[async-await-in-swift]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[swift-6]]></category>
            <dc:creator><![CDATA[Ali Akhtar]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 09:53:52 GMT</pubDate>
            <atom:updated>2025-02-12T09:53:52.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WM1TIYKnlU4MaBTu.jpeg" /><figcaption><a href="https://developer.apple.com/news/?id=2o3euotz">https://developer.apple.com/news/?id=2o3euotz</a></figcaption></figure><p>It is recommend to see<a href="https://ali-akhtar.medium.com/swift-new-concurrency-framework-part-3-701356819bb6"> part3</a> before continue this</p><h4><strong>Task</strong></h4><blockquote>A task provides a fresh execution context to run asynchronous code. Each task runs concurrently with respect to other execution contexts. They will be automatically scheduled to run in parallel when it is safe and efficient to do so. Because tasks are deeply integrated into Swift, the compiler can help prevent some concurrency bugs. Also, keep in mind that calling an async function does not create a new task for the call. You create tasks explicitly. There are a few different flavors of tasks in Swift.\</blockquote><p>As illustrated in Figure 1, there are a few key points to consider:</p><ul><li>Tasks can run in parallel or concurrently.</li><li>A task inherits the context of its parent thread. For example, if the parent thread is the main thread, the task will also run on the main thread.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PuGPu5RRa3u_DJDxMaANYA.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><p>As shown in Figure 2, I replaced Task with Task.detached, which resulted in an error.</p><p>When using Task.detached, it does not inherit the actor context (e.g., self in a class). Instead, it runs in a completely independent execution context. This means you must explicitly capture self when accessing instance properties or methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FK6vzWecmsRHI-4ArcRb1Q.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><p>As shown in Figure 3:</p><p>✅ Task.detached creates a completely independent task.<br>❌ It does not inherit the main thread context.</p><p>someTask run on the main thread. In Swift, methods inside UIViewController (or any UIKit class) implicitly inherit @MainActor. Even though Task.detached starts on a background thread, calling await self?.someTask() moves execution back to the main thread because someTask() belongs to UIViewController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLH6k968cwtF9uE2MN8Nyw.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><p>“As shown in Figure 4, I have now moved someTask to a new class, which is the ViewModel. Since someTask is asynchronous and no specific thread is specified, it will automatically run on a background thread.&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5lzbUFA4B618l46rFCGHg.png" /><figcaption><strong>Figure 4</strong></figcaption></figure><p>As shown in Figure 5, we have now removed Task.detached, and viewDidLoad() runs on the main thread. Since viewDidLoad() belongs to UIViewController, it always executes on the main thread.</p><p>Task {} inherits the caller&#39;s thread, which in this case is the main thread. Because Task {} is created inside viewDidLoad(), it starts execution on the main thread.</p><p>Does someTask run on a background thread? This can happen because Swift&#39;s concurrency model may offload work to a background thread when entering an `async` function, even if the Task was initially created on the main thread. Swift&#39;s concurrency model is designed to optimize performance by utilizing multiple threads.</p><p>The second print statement inside the someTask method, after await Task.sleep, also prints false, indicating that the code is still not running on the main thread. After await, the continuation of the Task may resume on a different thread (not necessarily the main thread). This is expected behavior in Swift concurrency, as the runtime determines the most efficient thread for resuming the task.</p><p><strong>The key takeaway is that Swift concurrency does not guarantee that an async function will run on the same thread where it was called. Even if the </strong><strong>Task is created on the main thread, the async function (</strong><strong>someTask) may execute on a background thread. The </strong><strong>await keyword suspends the task, allowing the runtime to decide which thread to use for resuming execution. This explains why both print statements inside </strong><strong>someTask—before and after </strong><strong>await—output </strong><strong>false.&quot;</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjeY4BSydX0akWn65HXRHg.png" /><figcaption><strong>Figure 5</strong></figcaption></figure><p>“Explicitly using @MainActor ensures that this method runs on the main thread. When working with Task, always check which thread the code is executing on. If no specific thread is specified, execution may be unpredictable. If you need a method to always run on the main thread, make sure to annotate it with @MainActor.&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpT6BWMFDhV8mHbrRVjxLQ.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><p>As shown in Figure 7, now we create another Task inside someTask which uses Parent thread which is backgorund so Task 2 noe using background thread,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIeeF_jcoXMhXJmmrZS33Q.png" /><figcaption><strong>Figure 7</strong></figcaption></figure><p>As shown in Figure 8, what I want is to run Task 2 execution context on Main thread , I can use that logic now to tell explicitly run on Main thread</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYQpa97PevFVCVltT1L1Wg.png" /><figcaption><strong>Figure 8</strong></figcaption></figure><p>“As shown in Figure 9, here’s a recap and summary:</p><ul><li>Task inherits the parent thread if no specific execution context is specified.</li><li>An async method may run on a background thread.</li><li>If you use Task.detached, it will not inherit the parent thread and will always run independently.</li><li>Using Task { @MainActor ... } ensures that the task runs on the main thread.</li><li>If an async function is not explicitly assigned an execution context, its execution thread can be unpredictable.</li></ul><p>Many people assume that the caller determines where an async function runs, which is understandable because traditionally, most code has worked this way. However, invoking Task from the main thread does not guarantee that it will continue execution on the main thread.</p><p>If you need execution to remain on the main thread, there are several options, as discussed.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uA6RmNAC8lyIfE3KscIa5w.png" /><figcaption><strong>Figure 9</strong></figcaption></figure><h3>Types of Task</h3><h4>1- async-let</h4><p>Let’s start with the simplest of these tasks, which is created with a new syntactic form called an async-let binding. To help you understand this new syntactic form,</p><p>Imagine you are building a weather app that needs to fetch two pieces of data concurrently:</p><ol><li>The current temperature for a city.</li><li>The current humidity for the same city.</li></ol><p>You want to fetch both pieces of data simultaneously and then combine them to display the weather information.</p><p>As you can see in <strong>Figure 11 this code currently </strong>fetchHumidity and fetchTemperature currently running sequentially , in background thread, but we want to fetch concurrently using async await</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOVSXbnmz3c-CWdVJdSoyQ.png" /><figcaption><strong>Figure 11</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OCSTV5D4_AgQwg2i1Bi2Q.png" /><figcaption><strong>Figure 12</strong></figcaption></figure><p>As shown in Figure 13, async let allows you to start multiple asynchronous tasks concurrently. In this example, fetchTemperature and fetchHumidity run at the same time, reducing the total time required to fetch both pieces of data. The fetchTemperature and fetchHumidity functions run on background threads because Swift concurrency automatically manages threads for asynchronous tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VAqY1Gwiv8otlhbwmcySng.png" /><figcaption><strong>Figure 13</strong></figcaption></figure><p>As shown in Figure 14 and Figure 15, we cancelled the task of , it is possible to cancel the task , but <strong>Temperature task is running.. called 21K times, </strong>Yes, the Output Suggests Task.sleep(nanoseconds:) Is Resuming Too Quickly After CancellationYour observations are on point. The cancellation of temperatureTask seems to cause Task.sleep(nanoseconds:) to <strong>wake up almost instantly instead of waiting for 200ms</strong>.since we are using try? This explains why &quot;Temperature task is running...&quot; is printing 15,000+ times <strong>after cancellation</strong>.Normally, Task.sleep(nanoseconds:) <strong>suspends execution</strong> for the given duration. However, if the Task gets <strong>canceled</strong>, Swift may <strong>wake it up immediately</strong> instead of waiting for the full sleep time. This is out of scope let’s see the best approach when you know Task can cancel,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HEXgzb2Ya-4dMyz0jtKe9A.png" /><figcaption><strong>Figure 14</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CskCAz3il8r2psGfORE0Xg.png" /><figcaption><strong>Figure 15</strong></figcaption></figure><p>Now we are properly catching an error instead of using `try?`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2S64bC3LOoA49sC2IAJQg.png" /><figcaption><strong>Figure 16</strong></figcaption></figure><p>As shown in Figure 17, we added a check if Task is cancelled or not , it is best practice You can check the cancellation status of the current task from any function, whether it is async or not. This means that you should implement your APIs with cancellation in mind, especially if they involve long-running computations. Your users may call into your code from a task that can be canceled, and they will expect the computation to stop as soon as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Grrlx0o5K7-B7F0-1RQq6Q.png" /><figcaption><strong>Figure 17</strong></figcaption></figure><p>Now after you added check `try?` also work without printing 21k times,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-hh7vxpaby3JYUHjW3uwA.png" /><figcaption><strong>Figure 18</strong></figcaption></figure><h4>Summary from WWDC</h4><p>Lets first break down the evaluation of an ordinary let binding. There are two parts: the initializer expression on the right side of the equals and the variable’s name on the left. There may be other statements before or after the let, so I’ll include those here too. Once Swift reaches a let binding, its initializer will be evaluated to produce a value. In this example, that means downloading data from a URL, which could take a while. After the data has been downloaded, Swift will bind that value to the variable name before proceeding to the statements that follow. Notice that there is only one flow of execution here, as traced by the arrows through each step. Since the download could take a while,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQokNIkJK23JGg_r-UqI-g.png" /><figcaption><strong>Figure 19</strong></figcaption></figure><p>Sinnce the download could take a while, you want the program to start downloading the data and keep doing other work until the data is actually needed. To achieve this, you can just add the word async in front of an existing let binding.This turns it into a concurrent binding called an async-let. The evaluation of a concurrent binding is quite different from a sequential one, <br>To evaluate a concurrent binding, Swift will first create a new child task, as shown in Figure 21, which is a subtask of the one that created it. Because every task represents an execution context for your program, two arrows will simultaneously come out of this step. This first arrow is for the child task, which will immediately begin downloading the data. The second arrow is for the parent task, which will immediately bind the variable result to a placeholder value.<br> This parent task is the same one that was executing the preceding statements. While the data is being downloaded concurrently by the child, the parent task continues to execute the statements that follow the concurrent binding. But upon reaching an expression that needs the actual value of the result, the parent will await the completion of the child task, which will fulfill the placeholder for result. In this example, our call to URLSession could also throw an error. This means that awaiting the result might give us an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4b5VvatgvvUxSCiQkvw7NA.png" /><figcaption><strong>Figure 20</strong></figcaption></figure><p>Whenever you make a call from one async function to another, the same task is used to execute the call. So, the function fetchOneThumbnail inherits all attributes of that task.</p><p>When creating a new structured task like with async-let, it becomes the child of the task that the current function is running on. Tasks are not the child of a specific function, but their lifetime may be scoped to it. The tree is made up of links between each parent and its child tasks. A link enforces a rule that says a parent task can only finish its work if all of its child tasks have finished. This rule holds even in the face of abnormal control-flow which would prevent a child task from being awaited.</p><p>For example, in this code, I first await the metadata task before the image data task. If the first awaited task finishes by throwing an error, the fetchOneThumbnail function must immediately exit by throwing that error. But what will happen to the task performing the second download? During the abnormal exit, Swift will automatically mark the unawaited task as canceled and then await for it to finish before exiting the function. Marking a task as canceled does not stop the task. It simply informs the task that its results are no longer needed. In fact, when a task is canceled, all subtasks that are decedents of that task will be automatically canceled too. So if the implementation of URLSession created its own structured tasks to download the image, those tasks will be marked for cancellation.</p><p>The function fetchOneThumbnail finally exits by throwing the error once all of the structured tasks it created directly or indirectly have finished. This guarantee is fundamental to structured concurrency. It prevents you from accidentally leaking tasks by helping you manage their lifetimes, much like how ARC automatically manages the lifetime of memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxBJ37oHMJeIFMAnKtpNfw.png" /><figcaption><strong>Figure 21</strong></figcaption></figure><h3>2- task group</h3><p>.The next kind of task I want to tell you about is called a group task. They offer more flexibility than async-let without giving up all of the nice properties of structured concurrency. As we saw earlier, async-let works well when there’s a fixed amount of concurrency available.Let’s create an example using async let and <strong>task groups</strong> (withTaskGroup) to demonstrate how you can perform multiple asynchronous tasks concurrently and collect their results. Task groups are particularly useful when you have a dynamic number of tasks or need to manage tasks in a structured way.</p><p>Imagine you are building a weather app that needs to fetch weather data for multiple cities concurrently. You want to use a task group to fetch the temperature for each city and then combine the results.</p><p>As shown in Figure 22 `withTaskGroup` allows you to run multiple tasks concurrently and collect their results in a structured way. Tasks are added to the group using group.addTask. ask groups are ideal when the number of tasks is dynamic (e.g., based on the number of cities). The for await loop collects results from the group as they become available.Results are returned in the order they complete, not necessarily the order they were added.</p><p>Also we avoid data races in here , we will see later how did we avoid data races</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxBgF24QHbSai_EB2aRrtw.png" /><figcaption><strong>Figure 22</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3DUbHy40L05v-Oe0mdhuQ.png" /><figcaption><strong>Figure 23</strong></figcaption></figure><p>If any task throws an error, the entire group will throw an error. You can handle errors using do-catch if needed. as shown in Figure 24</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeM-BX_rysfKEdFaMGnsHA.png" /><figcaption><strong>Figure 24</strong></figcaption></figure><p><strong>As shown in Figure 25 the app crash due to </strong>a data race issue. The problem is that we’re trying to insert a temperature into a single dictionary from each child task. This is a common mistake when increasing the amount of concurrency in your program.</p><p>Data races are accidentally created. This dictionary cannot handle more than one access at a time, and if two child tasks tried to insert temperature simultaneously, that could cause a crash or data corruption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9qpXGwqADIeOnuXLV--Hw.png" /><figcaption><strong>Figure 25</strong></figcaption></figure><p>Make sure you have this build setting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*P7WW-yUEh3thUjKpD8zrbA.png" /><figcaption><strong>Figure 26</strong></figcaption></figure><p>In the past, you had to investigate those bugs yourself, but Swift provides static checking to prevent those bugs from happening in the first place. Whenever you create a new task, the work that the task performs is within a new closure type called a `@Sendable` closure. The body of a @Sendable closure is restricted from capturing mutable variables in its lexical context, because those variables could be modified after the task is launched. This means that the values you capture in a task must be safe to share. For example, because they are value types, like Int and String, or because they are objects designed to be accessed from multiple threads, like actors, and classes that implement their own synchronization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LGDuG0gWSOU7mVteptg4w.png" /><figcaption><strong>Figure 27</strong></figcaption></figure><p>To avoid the data race in our example, you can have each child task return a value. This design gives the parent task the sole responsibility of processing the results. In this case, I specified that each child task must return a tuple containing the String ID and UIImage for the thumbnail. Then, inside each child task, instead of writing to the dictionary directly, I have them return the key value tuple for the parent to process. The parent task can iterate through the results from each child task using the new for-await loop. The for-await loop obtains the results from the child tasks in order of completion. Because this loop runs sequentially, the parent task can safely add each key value pair to the dictionary. This is just one example of using the for-await loop to access an asynchronous sequence of values. If your own type conforms to the AsyncSequence protocol, then you can use for-await to iterate through them too.</p><p>As shown in Figure 28, I fixed the old warning but new warning came</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypuG3XsjLije9H0yh7k6HQ.png" /><figcaption><strong>Figure 28</strong></figcaption></figure><p>Whenever you create a new task, the work that the task performs is within a new closure type called a `@Sendable` closure. Ask question is self is Sendable in our case its a ViewModel with class, if we convert it into struct this warning will remove</p><p>As shown in Figure 29, no warning at all with no data races</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfmTCF05wsrvYeTt7gMyUg.png" /><figcaption><strong>Figure 29</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFwD7oc_anQGJXDIhMp38g.png" /><figcaption><strong>Figure 30</strong></figcaption></figure><h3>3- Unstructured Task</h3><p>But we know that you don’t always have a hierarchy when you’re adding tasks to your program. Swift also provides unstructured task APIs, which give you a lot more flexibility at the expense of needing a lot more manual management. There are a lot of situations where a task might not fall into a clear hierarchy. Most obviously, you might not have a parent task at all if you’re trying to launch a task to do async computation from non-async code. as shown in Figure 31, Alternatively, the lifetime you want for a task might not fit the confines of a single scope or even a single function. You may, for instance, want to start a task in response to a method call that puts an object into an active state and then cancel its execution in response to a different method call that deactivates the object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSepdxSeacT_ELRmVpXPxA.png" /><figcaption><strong>Figure 31</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZ8IdL8h79Mbe0tY7thLNA.png" /><figcaption><strong>Figure 32</strong></figcaption></figure><p>Let’s say we have a collection view, and we can’t yet use the collection view data source APIs. Instead, we want to use our fetchThumbnails function we just wrote to grab thumbnails from the network as the items in the collection view are displayed. However, the delegate method is not async, so we can’t just await a call to an async function. We need to start a task for that, but that task is really an extension of the work we started in response to the delegate action. We want this new task to still run on the main actor with UI priority. We just don’t want to bound the lifetime of the task to the scope of this single delegate method. For situations like this, Swift allows us to construct an unstructured task. Let’s move that asynchronous part of the code into a closure and pass that closure to construct an async task. Now here’s what happens at runtime. When we reach the point of creating the task, Swift will schedule it to run on the same actor as the originating scope, which is the main actor in this case. Meanwhile, control returns immediately to the caller. The thumbnail task will run on the main thread when there’s an opening to do so without immediately blocking the main thread on the delegate method. Constructing tasks this way gives us a halfway point between structured and unstructured code. A directly constructed task still inherits the actor, if any, of its launched context, and it also inherits the priority and other traits of the origin task, just like a group task or an async-let would. However, the new task is unscoped. Its lifetime is not bound by the scope of where it was launched. The origin doesn’t even need to be async. We can create an unscoped task anywhere. In trade for all of this flexibility, we must also manually manage the things that structured concurrency would have handled automatically. Cancellation and errors won’t automatically propagate, and the task’s result will not be implicitly awaited unless we take explicit action to do so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WG8QQbxjCii0Sj9LgQ_Sew.png" /><figcaption><strong>Figure 33</strong></figcaption></figure><p>So we kicked off a task to fetch thumbnails when a collection view item is displayed, and we should also cancel that task if the item is scrolled out of view before the thumbnails are ready. Since we’re working with an unscoped task, that cancellation isn’t automatic. Let’s implement it now. After we construct the task, let’s save the value we get. We can put this value into a dictionary keyed by the row index when we create the task so that we can use it later to cancel that task. We should also remove it from the dictionary once the task finishes so we don’t try to cancel a task if it’s already finished. Note here that we can access the same dictionary inside and outside of that async task without getting a data race flagged by the compiler. Our delegate class is bound to the main actor, and the new task inherits that, so they’ll never run together in parallel. We can safely access the stored properties of main actor-bound classes inside this task without worrying about data races. Meanwhile, if our delegate is later told that the same table row has been removed from the display, then we can call the cancel method on the value to cancel the task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gW-EuC-SBBCRaX-hmjFgTQ.png" /><figcaption><strong>Figure 34</strong></figcaption></figure><h3>4- Detached Task</h3><p>So now we’ve seen how we can create unstructured tasks that run independent of a scope while still inheriting traits from that task’s originating context. But sometimes you don’t want to inherit anything from your originating context. For maximum flexibility, Swift provides detached tasks. Like the name suggests, detached tasks are independent from their context. They’re still unstructured tasks. Their lifetimes are not bound to their originating scope. But detached tasks don’t pick anything else up from their originating scope either. By default, they aren’t constrained to the same actor and don’t have to run at the same priority as where they were launched. Detached tasks run independently with generic defaults for things like priority, but they can also be launched with optional parameters to control how and where the new task gets executed.</p><p>Let’s say that after we fetch thumbnails from the server, we want to write them to a local disk cache so we don’t hit the network again if we try to fetch them later. The caching doesn’t need to happen on the main actor, and even if we cancel fetching all of the thumbnails, it’s still helpful to cache any thumbnails we did fetch. So let’s kick off caching by using a detached task. When we detach a task, we also get a lot more flexibility in setting up how that new task executes. Caching should happen at a lower priority that doesn’t interfere with the main UI, and we can specify background priority when we detach this new task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKVSMibbTgVvttb6HUxtaQ.png" /><figcaption><strong>Figure 35</strong></figcaption></figure><p>Let’s plan ahead for a moment now. What should we do in the future if we have multiple background tasks we want to perform on our thumbnails? We could detach more background tasks, but we could also utilize structured concurrency inside of our detached task. We can combine all of the different kinds of tasks together to exploit each of their strengths. Instead of detaching an independent task for every background job, we can set up a task group and spawn each background job as a child task into that group. There are a number of benefits of doing so. If we do need to cancel the background task in the future, using a task group means we can cancel all of the child tasks just by canceling that top level detached task. That cancellation will then propagate to the child tasks automatically, and we don’t need to keep track of an array of handles. Furthermore, child tasks automatically inherit the priority of their parent. To keep all of this work in the background, we only need to background the detached task, and that will automatically propagate to all of its child tasks, so we don’t need to worry about forgetting to transitively set background priority and accidentally starving UI work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZI7DYIKNjcI0XQ5DXS5Y9g.png" /><figcaption><strong>Figure 36</strong></figcaption></figure><p>Async-let allows for a fixed number of child tasks to be spawned as variable bindings, with automatic management of cancellation and error propagation if the binding goes out of scope. When we need a dynamic number of child tasks that are still bounded to a scope, we can move up to task groups. If we need to break off some work that isn’t well scoped but which is still related to its originating task, we can construct unstructured tasks, but we need to manually manage those. And for maximum flexibility, we also have detached tasks, which are manually managed tasks that don’t inherit anything from their origin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlWif4KB4QnHzRB-_My_qg.png" /><figcaption><strong>Figure 37</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a691120eee2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pluggable Domain Component in iOS]]></title>
            <link>https://medium.com/hungerstation/pluggable-domain-component-in-ios-405cb8938c83?source=rss-ec9cefb72e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/405cb8938c83</guid>
            <category><![CDATA[ui-component]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[modularization]]></category>
            <dc:creator><![CDATA[Ali Akhtar]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 13:39:18 GMT</pubDate>
            <atom:updated>2023-01-23T11:01:59.415Z</atom:updated>
            <content:encoded><![CDATA[<p>In mobile apps, sometimes screens are considered the real estate of the software we are developing, where each screen or group of screens belongs to a single domain/team. However it can sometimes happen that this real estate (screen) is too big to be handled by one domain. In this article we will look at how to create domain components that has embedded business logic, data preparation, rendering logic, tracking, and many more so that it can easily be pluggable into any screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*jjoZIRyVHqeooIkmmOd_9Q.jpeg" /></figure><p>In the HungerStation app, we have the Order Tracking screen, where the user can see the placed order information. <strong>Gif 1 </strong>represents a simplified version of the screen and contains the following components:</p><ul><li>Payment Information</li><li>Restaurant Information</li><li>Delivery Information</li><li>Estimated Time the order delivery is expected</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*sC5ByGk5njIhuTxMLUzu7w.gif" /><figcaption><strong>Gif 1</strong></figcaption></figure><h3>Classes Structure</h3><p>In order to demonstrate the concept of building a pluggable component, let’s keep the structure as simple as possible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p91PSNOIFKYSdTihTaEKPg.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><h3>Data Flow</h3><ul><li>The data flow starts with viewDidLoad where we did two things called our endpoint which returns the whole data of the order tracking screen response and the second thing we called our OrderTrackingView to show a skeleton view until we get the response from the server. The response looks like as shown in <strong>gist 2:</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea1e22f1d7762acafa416685ecc07cdf/href">https://medium.com/media/ea1e22f1d7762acafa416685ecc07cdf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87101bcd5df9225fd1c7a64b303eec86/href">https://medium.com/media/87101bcd5df9225fd1c7a64b303eec86/href</a></iframe><p>Once we got the response we called configureContainerView the method that renders data in UI as shown above in <strong>Gif 3. </strong>Furthermore, you will see View / Components only hold the rendering logic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb694defd9a189e1da514cd37bf03c83/href">https://medium.com/media/fb694defd9a189e1da514cd37bf03c83/href</a></iframe><h3>Problems with this Approach</h3><p>To give a little bit more context; the teams here at HungerStation are divided into squads, where each squad is cross-functional, autonomous teams (typically 6–12 individuals) and are focused on part of the business domain. These business domains can span anywhere from one screen to multiple screens. Those screens are not necessarily mutually exclusive, and so it can happen that multiple squads are contributing to the same real estate/screen, each with his own domain. Here is the list of problems we can identify by looking at our current approach to building this screen:</p><h4>Problem 1 → Poor horizontal scalability</h4><p>This is the main engineering problem since there is a lot of <strong>shared</strong> code between multiple squads which includes API calls, parsing, and data preparation for UI components that lead to multiple bugs, conflicts, etc. directly impacting delivery and business goals.</p><h4>Problem 2 → Single Point of failure</h4><p>As you can see in Figure 1, due to a bug introduced by the payments squad backend (logo_s instead of logo) in response data that failed decoding ultimately fails the whole parsing logic and nothing will render in the Order Tracking screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfu_zqYRQHBdV-R3ElTabw.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><h4>Problem 3 → Monolith or bad modularisation</h4><p>While the single monolithic application approach may work well for simple mobile applications, surely there is a better way to build large complex mobile applications that have several different functional elements, in different modules. In our case, if every squad will create a separate module that can run independently it will create huge benefits that include reusability, module/feature isolation, etc.</p><h3>Brainstorming</h3><p>Our Order tracking screen should treat components as a black box which means it doesn’t know how to create data for this component, how to render it, and how to apply the business logic of that component. To accomplish this, we should create some contract allowing external modules/components to receive the state of the Order tracking screen and report back to it. Let me use the PaymentDetails section as an example to show you how we transformed it as a black box and how we transformed our Order Tracking screen from a monolith into a modular which can plug black box components into it. In the next section, we will step by step convert our idea into a prototype with some code snippets.</p><p><strong>Step 1 → Create Container View With State</strong></p><p>In this step, we will do the following things:</p><ul><li>Create a PaymentDetailsContainerView.</li><li>In the container view, we will put this component skeleton/loading view and the actual view inside vertically stackView when we need to show the loading view we will set the state to .loading , and once we get data we will set the state to .info with data.</li><li>Last thing we do we will create a separate module for each squad. This is very important since now we fix the issue of the Monolith application as shown in Figure 2 we create Payments, Order and Location modules. In Core the module we will put shared/common things which can be used by all these modules.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*nmyqb2BjqIcPTJtVg5EEWQ.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><p><strong>Step 2 → API / Response Break Down</strong></p><p>This step is crucial to make this component pluggable and it requires some backend changes as well. As shown in <strong>Gist 5 </strong>you can clearly see now this component is hitting its own endpoint that returns data relevant to that component only. In addition, it is also preparing data for its UI, applying business logic, and rendering UI as usual.</p><p>With this step, we eliminated the <strong>single point of failure problem</strong>. In addition to this, we also moved this component business logic from the main component which makes the main component lightweight that indirectly reduces the code conflict and code duplication.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14c43c9970f9f8ef0b68ae3e1aaac21a/href">https://medium.com/media/14c43c9970f9f8ef0b68ae3e1aaac21a/href</a></iframe><p><strong>Step 3 → View Loadable Class</strong></p><p>In this step, we will create an interface for our pluggable component, the name of this class is debatable. Any module or screen wants to load Payment Details should talk to this class. The responsibilities of this class include:</p><ul><li>Load Payment Details View black box component into a parent view provided by the client, it can load either skeleton or actual view as per internal logic, the client doesn’t care about anything, the client only calls renderView and provided only the componentId and superView and our pluggable component handle all tasks related to it as we saw in <strong>Gist 5.</strong></li><li>Output some events to the client to react in our case we are outputting only hide events, so the hiding logic will implement by the client.</li><li>The Input communication to the component is PaymentDetailsViewLoadable</li><li>The output communication of the component is PaymentDetailLoadableOutput</li><li>We created bidirectional communication between the client and component by using the above two classes.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7970d72e27d8ee8b345a8a78b8c92fb5/href">https://medium.com/media/7970d72e27d8ee8b345a8a78b8c92fb5/href</a></iframe><p><strong>Step 4 → Integration Part</strong></p><p>In the integration part, the client has to do the following things:</p><ul><li>Inject PaymentDetailsViewLoadable input interface with a concrete class PaymentDetailsViewLoader</li><li>Create container view paymentDetailsViewContainer and add constraints where the client wants to load our component.</li><li>Call renderView and provide componentId which will use to get the component data plus paymentDetailsViewContainer where our component will add as a subview.</li><li>Listen to components events paymentDetailsInjector.output , and react accordingly in the case we only have to hide. Hiding the logic of the component is the responsibility of the client, we need to do this for all our components.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7090d3d28ba2f562a947008fa0c0bd16/href">https://medium.com/media/7090d3d28ba2f562a947008fa0c0bd16/href</a></iframe><h3>Conclusion</h3><p>As shown in Gif2 we implement the Payment Summary component using modular/pluggable technique. If we compare this technique with the one where the main container was interfering with every components matter we see clear benefits. Here is the list of advantages we can observe:</p><ul><li>The component can easily plug into any screen.</li><li>Component business logic, UI data preparation, API, and rendering logic are embedded in their own space which reduces code conflict, and code duplication and it’s easy to scale new components into that screen.</li><li>No more single point of failure.</li><li>Lightweight container code or less shared code between multiple squads.</li><li>Fewer bugs.</li><li>Every squad can work independently.</li><li>Code changes can be easily automated and assigned to code owners.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*h7BGrdnNbpiuixhjtc7yLA.gif" /><figcaption><strong>Gif 2</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=405cb8938c83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hungerstation/pluggable-domain-component-in-ios-405cb8938c83">Pluggable Domain Component in iOS</a> was originally published in <a href="https://medium.com/hungerstation">HungerStation</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Height UITableView]]></title>
            <link>https://ali-akhtar.medium.com/dynamic-height-uitableview-20759e136caf?source=rss-ec9cefb72e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/20759e136caf</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[intrinsic-content-size]]></category>
            <category><![CDATA[content-size]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uitableview]]></category>
            <dc:creator><![CDATA[Ali Akhtar]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 18:10:48 GMT</pubDate>
            <atom:updated>2022-12-17T18:10:48.668Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z-f6tNSajWQblloG.png" /><figcaption><a href="https://developer.apple.com/documentation/uikit/uitableview"><strong>https://developer.apple.com/documentation/uikit/uitableview</strong></a></figcaption></figure><h3>Prerequisite</h3><p>You are pro developer using UITableView and AutoLayout. Also this blog is written to document thing what I learned so ignore some spelling mistake and other stuff if you understand it will be good and if something confusing comment</p><h3>UITableView</h3><p>A view that presents data using rows in a single column. Table views in iOS display rows of vertically scrolling content in a single column. Each row in the table contains one piece of your app’s content. For example, the Contacts app displays the name of each contact in a separate row, and the main page of the Settings app displays the available groups of settings. You can configure a table to display a single long list of rows, or you can group related rows into sections to make navigating the content easier.</p><h3>Getting Started</h3><p>As shown in Gist and Figure 1, we created simple tableView with fixed height 300</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5a8e7410a701871f253cebc99be50cb/href">https://medium.com/media/a5a8e7410a701871f253cebc99be50cb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7bFPTa_MvBycDv5wDAtSwA.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><p>As shown in Gif 1 , this device has lots of space but we fixed the height of UITableView scrolling started and we are not using the space wisely. What I want is to dynamically increase the height of UITableView According to its children size,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*hGr20NY00aUdg9keSkpFOw.gif" /><figcaption><strong>Gif 1</strong></figcaption></figure><p>As shown in <strong>Gif2 </strong>now height of UITableView dynamically increases , according to child contents, By doing few things. Lets talk about few things</p><ul><li><strong>contentSize →</strong> contentSize defines how big the scrollable content is. It is the size of the content within the UIScrollView and how long it can be within the UIScrollView. The scroll view must know the size of the content-view so it knows when to stop scrolling. its default value is zero, and it must be set to use any scroll view, even if the content-size is smaller than the scroll view’s own size. When TableView rendered it’s whole content it set this value A/C to total size of the content. It includes UI that not displaying at all in the screen → total size of content automatically created appearing or not appearing in scree</li><li><strong>noIntrinsicMetric → </strong>The absence of an intrinsic metric for a given numeric view property. In short it rely on auto layout algorihtm size calculation</li><li><strong>intrinsicContentSize →</strong> Custom views typically have content that they display of which the layout system is unaware. Setting this property allows a custom view to communicate to the layout system what size it would like to be based on its content. This intrinsic size must be independent of the content frame, because there’s no way to dynamically communicate a changed width to the layout system based on a changed height, for example. If a custom view has no intrinsic size for a given dimension, it can use noIntrinsicMetric for that dimension.</li><li><strong>invalidateIntrinsicContentSize →</strong> Invalidates the view’s intrinsic content size .Call this when something changes in your custom view that invalidates its intrinsic content size. This allows the constraint-based layout system to take the new intrinsic content size into account in its next layout pass.</li></ul><p><strong>Explanation:</strong></p><p>In Figure 2 and 3 what is happening ,</p><ul><li>First we remove the height constraint of UITableView, which will lead to autolayout ambigious height error since UITableView</li><li>Once tableview contentSize (which is autucal size whole content we have) we called invalidateIntrinsicContentSize which basically called intrinsicContentSize . Rember contentSize is the size of content in tableview whereas intrinsicContentSize is the tableView height where you see content so if intrinsicContentSize &lt; contentSize it means it can scroll since content view is more than the one who is showing content which is tableview</li><li>In short what we did we tell tableview use autolayout for everything except for height, height I will provide and when I will provide once my whole contentSize is rendered and it automatically know its content height, so my height of tableview is same as it’s content</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sP8N4IthmXnUHA6gjY91-Q.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4WgcUMgJst4GJKJH2mSmIA.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*48fyq_Y_1MKxrsWRIEMHZQ.gif" /><figcaption><strong>Gif 2</strong></figcaption></figure><p>As shown in Figure <strong>Figure 4 , here </strong><strong>return</strong> CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric) which means use autolayout only, but we remove the height constraint previously that’s why for autolauout height is ambigious</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmoamIcKhOgIjgv1UsoOVw.png" /><figcaption><strong>Figure 4</strong></figcaption></figure><p><strong>Problem1 : </strong>As you can see in Gif 2 if the intrinsic content size of tableview (which is it’s height) is equal to content size.height . but why tableView is still scrolling and the answer is as shown in Figure 5, <strong>adjustedContentInset </strong>value is 34 which means in simple word we are telling our content view to start from 34 which means our tableview actual contentSize height is 589.33333333333326 , and the tableview height (intrinsic size) is 589.33333333333326 (since contentSize height == tableview height when we do invalidateIntrinsicContentSize). But the scrollabale area of tablview is (589.33333333333326 + 34) which is contentSize height + <strong>adjustedContentInset, </strong>that’s why it is scrolling and you see scrollable bar also showing</p><p><strong>adjustedContentInset → </strong>The insets derived from the content insets and the safe area of the scroll view. Use this property to obtain the adjusted area in which to draw content. The contentInsetAdjustmentBehavior property determines whether the safe area insets are included in the adjustment. The safe area insets are then added to the values in the contentInset property to obtain the final value of this property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbTvfj33Ll7dC0GpOp0JsA.png" /><figcaption><strong>Figure 5</strong></figcaption></figure><p>The solution to this problem is we set the tbl.contentInsetAdjustmentBehavior = .never which Do not adjust the scroll view insets.</p><p><strong>contentInsetAdjustmentBehavior → </strong>The behavior for determining the adjusted content offsets. This property specifies how the safe area insets are used to modify the content area of the scroll view. The default value of this property is UIScrollView.ContentInsetAdjustmentBehavior.automatic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMKVrws3LLhxlvQYmqhRQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHYC-ELsmXGo-n5HMTRkqg.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*yfHcLT2PMsL4OyLUaBX3Pw.gif" /><figcaption><strong>Gif 3</strong></figcaption></figure><p><strong>Problem2 :</strong></p><p>Now see no content offset is added by tableview and there is no scroll bar at the right which means out content height is now perfectly same as height of tableview, but still you see it can scroll and the truth is it is not scrolling only scroll view bounces past the edge of content and back again</p><p><strong>bounces →</strong> A Boolean value that controls whether the scroll view bounces past the edge of content and back again.If the value of this property is true, the scroll view bounces when it encounters a boundary of the content. Bouncing visually indicates that scrolling has reached an edge of the content. If the value is false, scrolling stops immediately at the content boundary without bouncing. The default value is true.</p><p>As shown in Figure 7, we set <strong>bounces</strong> to false, now our tableview appear as a view no scrolling or anything and grows dynamically, people will ask why not stackview for these type of case yes we can use stackview but I will show one use case where we need this type of thing but tableview</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FoSdz1k58hYK750Z2SIRlg.png" /><figcaption><strong>Figure 7</strong></figcaption></figure><p>Now think about this case where content is too large that it actually can’t come on this screen , if we implement this with stackView we need to add lots of logic to make it scrollable by manually doing height calculation and embedded stackView in scrollView, but with tableView we can implement some simple logic to achieve this thing, like to enable scrolling when you reach some height limit,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3JTHa018gbur1LRKaSW5w.png" /><figcaption><strong>Figure 8</strong></figcaption></figure><p>As shown in Figure 9 , we specify max height threshold of our tableview and say if height is less than (screen height — 100) don’t enable scrolling and make the height of tableview same as its content which will not make tablview scrollable , but if it is greater than this then allow tableview to scroll and also make its height (screen height — 100) which is obviously less than its content size which auto do scrolling of isScrollEnabled is true</p><p><strong>isScrollEnabled → </strong>A Boolean value that determines whether scrolling is enabled.The default value is true, which indicates that scrolling is enabled. Setting the value to false disables scrolling.<br>When scrolling is disabled, the scroll view doesn’t accept touch events; it forwards them up the responder chain. Note intially in example we can use this thing as well but to understand <strong>contentInsetAdjustmentBehavior </strong>I didn’t do this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5H9a5NBY5kXJ0tn3DJMUOg.png" /><figcaption><strong>Figure 9</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20759e136caf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Course — Message Communication between Flutter and iOS Native Code]]></title>
            <link>https://ali-akhtar.medium.com/flutter-course-message-communication-between-flutter-and-ios-native-code-78494ed47c1e?source=rss-ec9cefb72e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/78494ed47c1e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter-platform-channel]]></category>
            <dc:creator><![CDATA[Ali Akhtar]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 18:51:24 GMT</pubDate>
            <atom:updated>2022-12-16T07:54:19.883Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Course — Message Communication between Flutter and iOS Native Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xuOeXjF_iX0brhrg.png" /><figcaption><a href="https://www.alibabacloud.com/blog/is-xianyu-quietly-giving-up-flutter_597991">https://www.alibabacloud.com/blog/is-xianyu-quietly-giving-up-flutter_597991</a></figcaption></figure><p>It will be good if you read this <a href="https://ali-akhtar.medium.com/flutter-course-use-flutter-in-existing-ios-project-8149a5579d19">blog</a> before continue reading this one. Here are the few terms you should know</p><p><strong>host →</strong> Native iOS code. Also called <strong>platform</strong></p><p><strong>Flutter portion →</strong> having flutter , dart code (also called client or UI )</p><p><strong>platform channel →</strong> host and flutter portion communication channels send and receive message</p><ul><li>Messages are passed between the client (UI) and host (platform) using platform channels as illustrated in this diagram: Messages and responses are passed asynchronously, to ensure the user interface remains responsive.</li><li>Even though Flutter sends messages to and from Dart asynchronously, whenever you invoke a channel method, you must invoke that method on the platform’s main thread.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*gjby2yAwitGE5ric.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><h3>Send Message to Native iOS Code</h3><p>We will use the same code that we previously write here in this <a href="https://ali-akhtar.medium.com/flutter-course-use-flutter-in-existing-ios-project-8149a5579d19">blog</a></p><p>First is to import these files</p><pre>import &#39;package:flutter/services.dart&#39;;<br>import &#39;dart:async&#39;;<br></pre><p>As shown in Figure 2 we did a few things</p><ul><li>The client and host sides of a channel are connected through a channel name passed in the channel constructor MethodChannel. All channel names used in a single app must be unique; prefix the channel name with a unique ‘domain prefix’, for example: my_flutter_app.sendMessage. MethodChannel exists in import ‘package:flutter/services.dart’;</li><li>Next, invoke a method on the method channel, specifying the concrete method to call using the String identifier sendMessage. The call might fail—for example, if the platform doesn’t support the platform API (such as when running in a simulator), so wrap the invokeMethod call in a try-catch statement.</li><li>Use the returned result to update the user interface state in _messageText inside setState.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLFj69hXN9mn1mJ0v3RBeA.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><p>As shown in Figure 3 , when we tap on button _sendMessageToNativeCode method will execute that will communicate to our native code, Here we are showing Text(_messageText) return by our native code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSDoGd4mKcxp3TzUjslZUg.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><p>As shown in Figure 4, here we handle code to receive message in native code send by our flutter portion code , here are the few things</p><ul><li>create a FlutterMethodChannel tied to the channel name my_flutter_app.sendMessage</li><li>add the iOS Swift code callSomeMethod that currently return some hard coded message as a result , note since this code is async you can do whatever you want , call some API, logging everything</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xi844JNmUWtsliCA6WJmSw.png" /><figcaption><strong>Figure 4</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*9vIJfI_xKR4gZ2DSZudgBw.gif" /><figcaption><strong>Gif1</strong></figcaption></figure><h3>Send Message to Native iOS Code with param using manual technique</h3><p>As shown in Figure 5, we are now passing Map&lt;String, String&gt; to native iOS code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJdC3EQFzu0GQi-7Dmfd3A.png" /><figcaption><strong>Figure 5</strong></figcaption></figure><p>As shown in Figure 6, we are now parsing these param value and combining these value to our hardcoded string and sending back to flutter code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jCxeMP3Bmt8epEIa0S__Q.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*TRKzruIZ6TPbvfUSDnGLiQ.png" /><figcaption><strong>Figure 7</strong></figcaption></figure><h3>Send Message to Native iOS Code with param using code generation libraries</h3><p>To include json_serializable in your project, you need one regular dependency, and two <em>dev dependencies</em>. In short, <em>dev dependencies</em> are dependencies that are not included in our app source code—they are only used in the development environment.</p><p>As show in Figure 8, we add new packages, and save it , it will automatically install this package it not so you can run this command in terminal in flutter portion of git sub module</p><pre>flutter pub get</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUFDI6ElEIRIwBtM_jZQ5A.png" /><figcaption><strong>Figure 8</strong></figcaption></figure><p>As shown in Figure 9 , we created a class name User but we get some error. These errors are entirely normal and are simply because the generated code for the model class does not exist yet. To resolve this, run the code generator that generates the serialization boilerplate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2VonPpPcN5FKwByGumK-lA.png" /><figcaption><strong>Figure 9</strong></figcaption></figure><p>By running flutter pub run build_runner build — delete-conflicting-outputs in the project root, you generate JSON serialization code for your models whenever they are needed. This triggers a one-time build that goes through the source files, picks the relevant ones, and generates the necessary serialization code for them. As shown in <strong>Figure 10 </strong>now error gone</p><blockquote>remember, you have to run the build manually every time you make changes in your model classes.</blockquote><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLRZG8x2vlY8efzkr1g8hQ.png" /><figcaption><strong>Figure 10</strong></figcaption></figure><p>As shown in Figure 11, we did few things</p><ul><li>Create user model instance and populate with data</li><li>using import ‘dart:convert’; lib we convert model to json string that will pass to our native code</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eB4zKc8dfwObqgo0VIhzcA.png" /><figcaption><strong>Figure 11</strong></figcaption></figure><p>In our native code we parse it as String json and using swift Codable feature we convert it to User struct instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaCfX51CzH7BhW2iaFfZyw.png" /><figcaption><strong>Figure 12</strong></figcaption></figure><h3>Receive Message from Native iOS Code with param</h3><p>As shown in Figure 13, we created a class FlutterNativeCodeListenerMethodChannel , this class will be responsible for handling message from native code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lG62o2dE5QKRxrZjON9Hjw.png" /><figcaption><strong>Figure 13</strong></figcaption></figure><p>As shown in Figure 14, in main.dart main method we called configure method of FlutterNativeCodeListenerMethodChannel which basically create a MethodChannel and create a communication channel between native and flutter code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZJYdQ0hcvlcVBioajIkgQ.png" /><figcaption><strong>Figure 14</strong></figcaption></figure><p>As shown in Figure 15, we called setMethodCallHandler to handle message from native code , we expect string from native code , then we convert it into Map&lt;String, dynamic&gt; and finally User using dependency we previously installed, after that we update _messageText property setState callback which re-render build method for this screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHCgH-2mSoafKyeAk4n3rQ.png" /><figcaption><strong>Figure 15</strong></figcaption></figure><p>As shown in Figure 16, when user tap on button in native code , previously we are opening flutter screen, now we send message to flutter screen then open that screen,</p><p>Note : In AppDelegate didFinishLaunchingWithOptions we already warm up our flutter engine which means that flutter screen is loaded but not showing and also main.dart loaded as well and our listener is setup, so when user tap on button it first send message to flutter code which already warm up so it receive first callback update _messageText property and then we open flutter controller which basically show directly the screen with proper message as shown in Figure 17</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pPsT6UUohwnQuewWqJhIA.png" /><figcaption><strong>Figure 16</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ru5S0MBlDaKvK1VHjZ4gxA.png" /><figcaption><strong>Figure 17</strong></figcaption></figure><h3>Update git submodule</h3><p>As you see in previous <a href="https://ali-akhtar.medium.com/flutter-course-use-flutter-in-existing-ios-project-8149a5579d19">blog</a>, we are using flutter code using git submodule and we already see how we can update it, so in root folder of your native . platform code just run these commands</p><pre>cd my_flutter_app<br>git add .<br>git commit -m &#39;communication between platform&#39;<br>git push</pre><p>Now run git pull and quit source tree and open again , in my case, now our git sub module now pointing to latest master, push that code,</p><pre>git pull<br>cd my_flutter_app<br>flutter build ios --simulator<br>cd ..<br>pod install</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxWxfd_OoQ7sQnKU3r1qkw.png" /><figcaption><strong>Figure 18</strong></figcaption></figure><p>You can checkout code until this <a href="https://github.com/aliakhtar49/flutter-integration/tree/feat/blog-2">here</a></p><h3>Useful links</h3><ul><li><a href="https://docs.flutter.dev/development/data-and-backend/json#manual-encoding">JSON and serialization</a></li><li><a href="https://docs.flutter.dev/development/platform-integration/platform-channels?tab=type-mappings-swift-tab">Writing custom platform-specific code</a></li><li><a href="https://medium.com/software-engineers-toolbox/call-flutter-from-native-android-via-platform-channel-in-4-steps-3151f6535d2f">Call Flutter from Native Android via Platform Channel in 4 Steps</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78494ed47c1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Course — Use Flutter in Existing iOS Project]]></title>
            <link>https://ali-akhtar.medium.com/flutter-course-use-flutter-in-existing-ios-project-8149a5579d19?source=rss-ec9cefb72e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/8149a5579d19</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gitsubmodule]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ali Akhtar]]></dc:creator>
            <pubDate>Sun, 11 Dec 2022 08:54:35 GMT</pubDate>
            <atom:updated>2022-12-15T18:43:13.063Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Course — Use Flutter in Existing iOS Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z1QGHy6oKZHlACqB.png" /><figcaption><a href="https://www.alibabacloud.com/blog/is-xianyu-quietly-giving-up-flutter_597991"><strong>https://www.alibabacloud.com/blog/is-xianyu-quietly-giving-up-flutter_597991</strong></a></figcaption></figure><p>Flutter is an open-source UI software development kit created by Google. It is used to develop cross-platform applications for Android, iOS, Linux, macOS, Windows, Google Fuchsia, and the web from a single codebase. First described in 2015, Flutter was released in May 2017.</p><h3>Prerequisite</h3><p>You already installed flutter in your system, if not follow this <a href="https://docs.flutter.dev/get-started/install/macos">link</a>, Basic knowledge of flutter, dart and iOS native code</p><h3>Getting Started</h3><p>By Run the following command, you can see now, flutter standalone project is created as shown in Figure 2. The default timer application and you can run as an independent flutter project as well as showin in Figure 2</p><pre>flutter create --template module my_flutter_app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*4VJHczqA0mlFvkgPkGlnsA.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4pB8lnHxRC3lMrVPtN_Kw.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><p>As shown in Figure 3, This is native iOS code having simple application , which has one pod Kingfisher and the button in the center , what we need to do when we tap on button we need to open a flutter timer screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RvmRBtFQPuBRGgyjPreKwg.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><p>As shown in Figure 4, we copy whole my_flutter_app flutter project into roort directory of native iOS code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxrEnRgCv7ul5KASYaDfiQ.png" /><figcaption><strong>Figure 4</strong></figcaption></figure><ul><li>Add the following lines to your Podfile:</li></ul><pre>flutter_application_path = &#39;my_flutter_app&#39;<br>load File.join(flutter_application_path, &#39;.ios&#39;, &#39;Flutter&#39;, &#39;podhelper.rb&#39;)</pre><ul><li>For each Podfile target that needs to embed Flutter, call install_all_flutter_pods(flutter_application_path).</li></ul><pre>target &#39;MyApp&#39; do   <br>  install_all_flutter_pods(flutter_application_path)<br>end</pre><ol><li>In the Podfile’s post_install block, call flutter_post_install(installer).</li></ol><pre>post_install do |installer|<br>  flutter_post_install(installer) if defined?(flutter_post_install)<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reK13YuTVlHt_W2hIQ0ctg.png" /><figcaption><strong>Figure 5</strong></figcaption></figure><p>Then run pod install</p><p>As shown in Figure 6 , we created a FlutterEngine, exposed as a property, on app startup in the app delegate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jqsp11NIbI9ewOJ_x7lDQ.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><p>UIButton hooked to present a <a href="https://api.flutter.dev/objcdoc/Classes/FlutterViewController.html">FlutterViewController</a>. The FlutterViewController uses the FlutterEngine instance created in the AppDelegate. As you can see in Gif now when I tap on Button it open flutter screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBYz8cu5pSfp61XoXtVWlA.png" /><figcaption><strong>Figure 7</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*AoiAJmtbUPkMhg1IEK1wJA.gif" /><figcaption><strong>Gif 1</strong></figcaption></figure><h3><strong>Few Things</strong></h3><p>As shown in Figure 8 , There are two folders Development Pods where. we have flutter specific package , if you add more packages to the flutter pubspec it will appear but Flutter and FlutterPluginRegistrant you will see always that is basically doing everything . In Pods folder you will see your native code dependency like Kingfisher.</p><blockquote>Theoretically it can possible you can do some configuration and put your native pod dependency in Development Pods as well but for simplicity just ignore it</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*2VSlyO3wUiAg83NKYqVlbA.png" /><figcaption><strong>Figure 8</strong></figcaption></figure><p>Remember we added this in our podfile , you can find this file here as well , This is also doing magic to installed flutter and everything and make it avaiable to use in native iOS code</p><blockquote>Do not source control the .ios/ directory since it’s autogenerated.</blockquote><pre>flutter_application_path = &#39;my_flutter_app&#39;<br>load File.join(flutter_application_path, &#39;.ios&#39;, &#39;Flutter&#39;, &#39;podhelper.rb&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IumHN3yupqODgU7dnPY2GA.png" /><figcaption><strong>Figure 9</strong></figcaption></figure><p>As shown in Figure 10, we did a code changes in flutter (increment counter by 2) and run native code from application and it is reflecting , note we open my_flutter_app in VS that is located in the root of bative code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNOdhy5K96uEzyoo0R7FMg.png" /><figcaption><strong>Figure 10</strong></figcaption></figure><p>As shown in diff yellow rectangle is fine to push since it include podfile changes and our integration code but 2nd rectangle we don’t want to push since it has flutter code as well and we need to create some mechanism for that since we need to host flutter project into some another repo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mFGf2RQOzjL98LHWnfsoA.png" /><figcaption><strong>Figure 11</strong></figcaption></figure><h3>Git submodule</h3><p>A Git submodule is a git tool that allows a user to essentially add a Git repository as a subdirectory of another Git repository. The subdirectory repository will have its own Git system, which means it will have its own commits history, independent from your main repository. This allows you to be able to set your subdirectory to refer to a specific commit you may want to work with.</p><p>First delete my_flutter_app from native code root directoy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDS1pkbazJWKaOwzQC8_yQ.png" /><figcaption><strong>Figure 12</strong></figcaption></figure><p>By deleting this you see now our code diff showing what we change in our native code not our dependent library which is flutter build screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zrav76pry5EWeN27YmI1Qw.png" /><figcaption><strong>Figure 13</strong></figcaption></figure><p>As shown in Figure 14, we pushed our flutter timer application code into repo <a href="https://github.com/aliakhtar49/my_flutter_app">https://github.com/aliakhtar49/my_flutter_app</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_icvt5rBcyycBr2iQRbPAA.png" /><figcaption><strong>Figure 14</strong></figcaption></figure><p>Run application and you will get error since we deleted the flutter code folder, now run pod install you will get error as shown in <strong>Figure 16 </strong>since no podhelper.rb file exists</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r86UAtc3Rxtw2yPizmL-xg.png" /><figcaption><strong>Figure 15</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_aI745QcB5cxgNw6p4aCQ.png" /><figcaption><strong>Figure 16</strong></figcaption></figure><p>Go to this root directory of native code in terminal and run the following command as shown in Figure 17</p><pre>git submodule add https://github.com/aliakhtar49/my_flutter_app.git</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g90sPdT2pzz_XYu1wLvOIw.png" /><figcaption><strong>Figure 17</strong></figcaption></figure><p>As shown in Figure 18, now with git submodule it downloaded the flutter app and still if you run pod install , you will get same error since podhelper.rb still not exists , for that we need to install first flutter package , so in your native ios root code run following commands</p><pre>cd my_flutter_app<br>flutter build ios --simulator<br>cd ..<br>pod install</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGXk5U6DUWEaxQQoqCzdPw.png" /><figcaption><strong>Figure 18</strong></figcaption></figure><p>For other developer</p><ul><li>Clone native code</li><li>git submodule update — init — recursive (to download any sub git module)</li></ul><pre>cd my_flutter_app<br>flutter build ios — simulator<br>cd ..<br>pod install</pre><ul><li>Then run application</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gFtc_QOdJveNCVJx6djAA.png" /><figcaption><strong>Terminal Command</strong></figcaption></figure><p>Now pushed your native code with the integration is done successfully as you can see no file we are committing that is unknown to us , git submodule add <a href="https://github.com/aliakhtar49/my_flutter_app.git">https://github.com/aliakhtar49/my_flutter_app.git</a> auto generated .gitmodules file that keep track of git submodule as shown in Figure 19 and my_flutter_app in Figure 20 donot have entire folder instead commit potinging to out my_flutter_app git submodule</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wev4D_mUQ0F0t55R6Q21bg.png" /><figcaption><strong>Figure 19</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fuph7Z8YXgilH973TNA5A.png" /><figcaption><strong>Figure 20</strong></figcaption></figure><h3>Update The Flutter Code</h3><p><strong>Approach 1: </strong>Here we will first update in flutter repo then push code in flutter repo then update our native code to update to latest git submodule</p><p>As shown in Figure 21 , I updated the flutter code now our counter will increment by 3 instead of 2 and I pushed the code in my independent git submodule</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0sMhP7Z2V50GLyPwN-HWlw.png" /><figcaption><strong>Figure 21</strong></figcaption></figure><p>Now go the root directory of native ios code</p><pre>cd my_flutter_app  <br>git checkout master<br>git pull </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJjMP2uzH9C8ber2fpglgg.png" /></figure><p>After run above commands you will see now our native ios code pointing to latest flutter code (git submodule) code, now we can push this code , other developer when who take a pull from master need to run git submodule update — init — recursive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWIiwTB92EnrRoKDSCjTJQ.png" /><figcaption><strong>Figure 22</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ix2nQtuFQmN08XtR8TuCBg.png" /><figcaption><strong>Figure 23</strong></figcaption></figure><p><strong>Approach 2: </strong>Here we will update in flutter repo in the native code directly and locally test the code</p><p>As shown in Figure 24, we open flutter project directly from our native code and did changes which is increment counter by 5 and tested locally without pushing anything, now go to the root directoty of native code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3xQ6nGc5i5ueZD5LzDiPA.png" /><figcaption><strong>Figure 24</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6Ko1PpupGdGg-r20ZBGxA.png" /><figcaption><strong>Figure 25</strong></figcaption></figure><p>As shown in Figure 26, after we verify everything is working fine we pushed our flutter code changes directly from native code sub git repo, you can also create branch everything what you can do with git thingy</p><pre>cd my_flutter_app<br>git add .<br>git commit -m &#39;increment by 5&#39;<br>git push</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9AHeXC5liaz82WLziwUmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVFB4BOQSBjJ8HYSN7WNCg.png" /><figcaption><strong>Figure 26</strong></figcaption></figure><p>Now run git pull and quit source tree and open again , in my case as shown in Figure 27 now our git sub module now pointing to latest master, push that code, now out counter will increment by 5</p><pre>git pull</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lYSnipM9owRj8HCNd8R6A.png" /><figcaption><strong>Figure 27</strong></figcaption></figure><h3>Useful Links</h3><ul><li><a href="https://docs.flutter.dev/development/add-to-app/ios/project-setup">Integrate a Flutter module into your iOS project</a></li><li><a href="https://docs.flutter.dev/development/add-to-app/ios/add-flutter-screen?tab=vc-uikit-swift-tab">Adding a Flutter screen to an iOS app</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8149a5579d19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift New Concurrency Framework (Part 3)]]></title>
            <link>https://ali-akhtar.medium.com/swift-new-concurrency-framework-part-3-701356819bb6?source=rss-ec9cefb72e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/701356819bb6</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[async-streams]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ali Akhtar]]></dc:creator>
            <pubDate>Thu, 12 May 2022 09:51:47 GMT</pubDate>
            <atom:updated>2022-05-12T09:51:47.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LL6X4TMB4P2jpGTn.jpeg" /><figcaption><a href="https://developer.apple.com/news/?id=2o3euotz">https://developer.apple.com/news/?id=2o3euotz</a></figcaption></figure><p>It is mandatory to read <a href="https://ali-akhtar.medium.com/swift-new-concurrency-framework-part-2-7004822b7860">part2</a> before continue this</p><h3>Async Sequence</h3><p>A type that provides <strong>asynchronous</strong>, <strong>sequential</strong>, <strong>iterated</strong> access to its elements.AsyncSequence is a protocol describing a sequence that can produce elements asynchronously. Its surface API is identical to the Swift standard library’s Sequence, with one difference: You need to await the next element, since it might not be immediately available, as it would in a regular Sequence</p><p>OR<br>AsyncSequence. This protocol allows developers to asynchronously iterate over values coming from a sequence by awaiting them. This means that the sequence can generate or obtain its values asynchronously over time, and provide these values to a for-loop as they become available.</p><p>If this sounds familiar, that’s because a Combine publisher does roughly the same thing. A publisher will obtain or generate its values (asynchronously) over time, and it will send these values to subscribers whenever they are available.While the basis of what we can do with both AsyncSequence and Publisher sounds similar, I found this <a href="https://www.donnywals.com/comparing-use-cases-for-async-sequences-and-publishers/">link</a> where you see the roughly difference</p><h3>Getting Started</h3><p>As shown in Figure 1 this is <strong>synchronous, sequential iterated</strong> access to its elements which gives you element in array in sequence , it is not possible that you will get 6 before getting 1 to 5 which means <strong>sequential iterated</strong> access and <strong>synchronous means it will not suspend</strong></p><p>This is roughly what the compiler does when building the for-in loop. It first starts off by creating an iterator variable and then uses a while loop to get every item produced by the iterator when next is invoked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pe5_tZ4-YUE_H1pJ_kuY_g.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><p>As shown in Figure 2 we start off with a URL to an endpoint.It lists some mock text samples</p><ul><li>Now, normally downloading stuff is really an asynchronous task that can take some time.</li><li>But in this case, we don’t want to wait for all the things to download; instead, we want to show things as they are received so we use the new async/await features to get the lines responded from this endpoint.</li><li>Since the async sequence of lines is emitting each line as it’s received, that means we can potentially have a really large download ahead of us.</li><li>The snippet feels really responsive, and the most awesome part about it is that you can use the same things that you’re familiar with using from regular sequences in this new async context. which we will talk later. That means that you can use the new for-await-in syntax to iterate, and functions like map, dropFirst, filter, and reduce;</li><li>Recap async/await → Async functions let you write concurrent code without the need for callbacks, by using the await keyword.Calling an async function will suspend and then be resumed whenever a value or error is produced.</li><li>AsyncSequence, on the other hand, will suspend on each element and resume when the underlying iterator produces a value or throws.</li><li>as the name implies, they’re just like regular sequences but with a few key differences. 1) each element is delivered asynchronously. 2) But because they are an asynchronous delivery, that means that failure is definitely a possibility.Some async sequences throw, but if failure is not an option, others do not. Just like functions that throw, the compiler will help make sure that errors are handled when iterating or composing.</li><li>asynchronous sequences are a description of how to produce values over time. (In our case when new line available it produce value and give it )</li><li>So an async sequence may be zero or more values and then signify completion with returning a nil from its iterator, just like sequences.</li><li>When an error occurs, that’s also a point at which the async sequence is at a terminal state, and after an error happens, they’ll return nil for any subsequent calls to next on their iterator.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KB25fns7047kyzxRIUjcsA.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><p>In Figure 1 we saw how compiler basically transform for-in synchronous sequence. to use the new async/await functionality, there is one slight alteration that can be made.It’s as simple as changing that next function to be an asynchronous one.We can now have the iteration participate in Swift concurrency by awaiting the next line.</p><p>if the loop was on an async sequence.As previously mentioned, we need to await each item out of the async sequence.This is reflected in the new for-await-in syntax.This all means that if you know how to use Sequence, you already have a good idea on how to use AsyncSequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbhpcV5yxNv_B4Ngh-D2_A.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><p>Let’s next take a tour of some of the AsyncSequence APIs that are available as of macOS Monterey, iOS 15, tvOS 15, and watchOS 8.Reading from files is often a prime use case for asynchronous behavior.FileHandle now has a new bytes property that gives access to an asynchronous sequence of bytes from that FileHandle.This can be used in conjunction with the new extension on AsyncSequence that converts asynchronous sequences of bytes into lines.But dealing with files is so common that apple decided that URL should have accessors for both bytes and lines.This is that same API that we used in the initial example.It’s a convenience property on URL to return an AsyncSequence of lines from the contents, either from a file or from the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYtDo3PuwzSxzr2S7rGTEg.png" /></figure><p>In asynSequence we can use break and continue in the same way we use in normal sequence,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdEhXDf4H9_-GqTEApymIg.png" /><figcaption><strong>Figure 4</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOJN08VLsUXWpI3JGBLcsQ.png" /><figcaption><strong>Figure 5</strong></figcaption></figure><p>Pretty much anything you can think of for using on Sequence now has an asynchronous counterpart for working with AsyncSequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tm8WGpg_Lq7NVZ7X_2YYiA.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJa9zRV2CUoNNsyK5SJHmw.png" /></figure><p>As shown in <strong>Figure 7 </strong>This second iteration runs sequentially after the iteration of the first loop. Since inside Task context it run sequentially because of await like a normal sequence , You see difference Task vs Task.detached we will later part in detail but for now you can observer Task uses parent context thread which is Main Thread and Task.detached create thread and then work in a sequential manner</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qj8dypz96gFWd2RhYYPlqw.png" /><figcaption><strong>Figure 7</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLf8wR3q2wjH9sxOhmm7FA.png" /><figcaption><strong>Figure 8</strong></figcaption></figure><ul><li>Running code sequentially isn’t always what’s desired.If it’s useful to run the iteration concurrent to other things going on, you can create a new async task that encapsulates the iteration.</li><li>This can be useful when you know the async sequences you’re using might run indefinitely.</li><li>, even though that sequence could potentially be indefinite, it’s considerably less common to occur.But in the world of asynchronous behavior, it is something much more common and something that you need to consider when using them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSh6-Blw1S2tBWntnqRdNQ.png" /><figcaption><strong>Figure 9</strong></figcaption></figure><p>Here we can run the two iterations concurrently and terminate the iteration 1 later on. It’s pretty easy with tasks to scope the work of an iteration that might be indefinite to the lifetime of some container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bW-lHzrVrqn6nvv7OHn04g.png" /><figcaption><strong>Figure 10</strong></figcaption></figure><h3>Create Your Own Async Sequence</h3><h3>What is an AsyncThrowingStream?</h3><p>You can see an AsyncThrowingStream as a stream of elements that could potentially result in a thrown error. Values deliver over time, and the stream can be closed by a finish event. A finish event could either be a success or a failure once an error occurs.</p><h3>What is an AsyncStream?</h3><p>An AsyncStream is similar to the throwing variant but will never result in a throwing error. A non-throwing async stream finishes based on an explicit finished call or when the stream cancels.</p><p>As shown in Figure 11 and 12 we created FileDownloader service that download some big image and it gives you progress data how much image is downloaded</p><p>The file downloader reports a stream of values during the file download. In this case, it’s reporting a stream of status values to report the current status of the running download. The FileDownloader is a perfect example of a piece of code that you can rewrite to use AsyncStream</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZVqT6EpwCFtQvuB60_T7g.png" /><figcaption><strong>Figure 11</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDL_Vh6Fv_pOFt0duA2l0A.png" /><figcaption><strong>Figure 12</strong></figcaption></figure><p>As you can see, we wrapped the download method inside an AsyncStream. We describe the stream’s type of value Status as a generic, allowing us to continue the stream with status updates. On download image bytes by bytes we pass values to our stream utilizer. In the case of the completion handler, we’re either finishing by throwing an error or following up the yield with data with a non-throwing finish callback:</p><p>It’s essential to not forget about the finish() callback after you’ve received the final status update. Otherwise, we will keep the stream alive, and code at the implementation level will never continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FW_sMhBa7GOqdTtw_YODKA.png" /><figcaption><strong>Figure 13</strong></figcaption></figure><p>You can start iterating over the stream of values once you’ve configured your async throwing stream. In the case of our AsyncSequencFileDownloader example, it will look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMBrt0DnwLOZh98lzLZEYg.png" /><figcaption><strong>Figure 14</strong></figcaption></figure><p>Now I replace url with small size image you see image is download with progress bar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbknuvV6a39K1fgRfUdG3Q.png" /><figcaption><strong>Figure 15</strong></figcaption></figure><p>The callback is called on termination of the stream and will tell you whether your stream is still alive or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfw89uxuaMBYNmgZI4YyqA.png" /><figcaption><strong>Figure 16</strong></figcaption></figure><p>An AsyncStream or AsyncThrowingStream can cancel due to an enclosing task getting canceled. An example could look as follows:. A stream cancels when going out of scope or when the enclosing task cancels. As mentioned before, the cancellation will trigger the onTermination callback accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJydOIyau_I1rOA95CUOgQ.png" /><figcaption><strong>Figure 17</strong></figcaption></figure><p>As shown in Figure 18 and 19 we didn’t finish our AsyncStream so as a result onTermination not called</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQKDEyrom6bSZHrH21RJ3A.png" /><figcaption><strong>Figure 18</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9rht1tskefVwVkZ0vEg8w.png" /><figcaption><strong>Figure 19</strong></figcaption></figure><h3>Summary Of Create Own Async Sequence</h3><ul><li>Particularly, there are a few design patterns that work really well with AsyncSequence, Some of those design patterns are like closures that are called multiple times, but also some delegates can work nicely too. Like in previous example Pretty much anything that does not need a response back and is just informing of a new value that occurs can be a prime candidate for making an async sequence.</li><li>These design patterns are really common and you likely already have a few in your apps today.</li><li>This is an example of a common handler pattern.</li><li>It’s a class that has a handler property and a start and stop method.</li><li>It seems like a perfect candidate for AsyncSequence.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_D99bHmDB3NlFk87MEtyQ.png" /><figcaption><strong>Figure 20</strong></figcaption></figure><p>Existing usage might be something like this where a monitor is created, and a handler to get values is assigned, and then the monitor is started so that quakes can be sent to the handler.Later on, the monitor might be stopped to cancel the events being produced.We can use the same interface to adapt the usage to the new AsyncStream type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRvYLHmQe2mPfUn8jplKPw.png" /><figcaption><strong>Figure 21</strong></figcaption></figure><ul><li>It takes only a small bit of code to use it and allows you to build an async sequence.When constructing an async stream, an element type and construction closure is specified.</li><li>The closure has a continuation that can yield values more than once, finish, or handle termination.So this means, in this case, the monitor can be created inside the construction closure.And then the handler can be assigned to yield quakes to the continuation.And then the onTermination can handle the cancellation and cleanup.And then we can start monitoring.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWkf2s-tQ54I3g47wYkUCA.png" /><figcaption><strong>Figure 22</strong></figcaption></figure><ul><li>And this is how the usage of this async stream would work.You can use the powerful transformation functions — like filter — and the new for-await-in syntax.</li><li>This lets you focus on the intent of your code instead of needing to worry about replicating the bookkeeping, since everything is wrapped up into one place.There’s a lot of flexibility with AsyncStream to create your own async sequences.</li><li>This is really just one example and there are likely numerous others that you can adapt in your own code.</li><li>AsyncStream is a great way to adapt your existing code to become an async sequence.</li><li>It handles all of the things you would expect from an async sequence, like safety, iteration, and cancellation; but they also handle buffering.</li><li>AsyncStream is a solid way of building your own async sequences and a suitable return type from your own APIs, since the only source of elements being produced is from the construction.</li><li>And if you need to represent errors being thrown? Well, we have a type for that! AsyncThrowingStream that is just like AsyncStream but can handle errors.</li><li>It offers the same flexibility and safety as AsyncStream but can handle failures by throwing from its iteration.</li><li>AsyncSequence is a really powerful tool that is both safe and familiar for dealing with more than one asynchronous value.</li><li>If you know how to use Sequence, you already know how to use AsyncSequence.</li><li>We’ve gone over what async sequences are, and how they’re used, and introduced you to AsyncStream.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qbSXHyaJHDsb-mzSEl5_g.png" /><figcaption><strong>Figure 23</strong></figcaption></figure><h3>Create Own AsyncSequence using <strong>AsyncSequence Protocol</strong></h3><p>Before moving on please see my <a href="https://ali-akhtar.medium.com/ds-algorithm-linked-list-b4fcccba1fda">blog</a> where we created a LinkedList from scratch and we conform to Sequence Protocol, to access it as For-in loop , It is highly recommended</p><h3>Getting Started</h3><ul><li>Using AsyncSequence is almost identical to using Sequence, with the exception that your types should conform to AsyncSequence and AsyncIterator, and your next() method should be marked async. When it comes time for your sequence to end, make sure you send back nil from next(), just as with Sequence.</li><li>As you can see in <strong>Figure 24</strong>, we defined a DownloadSequenceImages struct that implements the AsyncSequence protocol. The protocol requires us to return a custom AsyncIterator We can now return self as the iterator and keep all logic centralized. Note that we have to help the compiler by providing the typealias to conform to the AsyncSequence protocol.</li><li>The next() method takes care of iterating overall values. Our example comes download image on reverse order to download all images until we reach the end. We implement cancellation support by making checking for Task.isCancelled. It’s very important</li><li>Now that we know what an AsyncSequence is and how it’s implemented under the hood, it’s time to start iterating over the values</li><li>We have to use the await keyword since we might receive values asynchronously. We exit the for loop once there are no values to be expected anymore. Implementors of an asynchronous sequence can indicate reaching the limit by returning nil in the next() method. In our case, we’ll reach that point once the counter reaches the configured limit or when the iteration cancels:</li><li>Many of the regular Sequence operators are also available for asynchronous sequences. The result is that we can perform operations like mapping and filtering in an asynchronous manner.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKvwHN_6DbGw2RKNuF4SSg.png" /><figcaption><strong>Figure 24</strong></figcaption></figure><h3>Useful Links</h3><ul><li><a href="https://www.avanderlee.com/swift/asyncthrowingstream-asyncstream/">AsyncThrowingStream and AsyncStream explained with code examples</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2021/10058/?time=664">Meet AsyncSequence - WWDC21 - Videos - Apple Developer</a></li></ul><p><a href="https://www.avanderlee.com/concurrency/asyncsequence/">https://www.avanderlee.com/concurrency/asyncsequence/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=701356819bb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DS & Algorithm (Linked List)]]></title>
            <link>https://ali-akhtar.medium.com/ds-algorithm-linked-list-b4fcccba1fda?source=rss-ec9cefb72e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4fcccba1fda</guid>
            <category><![CDATA[sequence]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[iterators]]></category>
            <category><![CDATA[collection]]></category>
            <dc:creator><![CDATA[Ali Akhtar]]></dc:creator>
            <pubDate>Wed, 11 May 2022 12:57:14 GMT</pubDate>
            <atom:updated>2022-05-12T09:53:03.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*Z84Oi3K8hWTVadhZ1hMkbw.png" /><figcaption><strong>Linked List</strong></figcaption></figure><p>A linked list is a collection of values arranged in a linear unidirectional sequence. A linked list has several theoretical advantages over contiguous storage options such as the Swift Array:<br>- Constant time insertion and removal from the front of the list.<br>- Reliable performance characteristics.</p><p>As the diagram suggests, a linked list is a chain of nodes. Nodes have two responsibilities:</p><ol><li>Hold a value</li><li>Hold a reference to the next node. A nil value represents the end of the list</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*oOhnOkIpxk61F8xlnhcowQ.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*1FU2bvztiu6LxA6HbWeCBw.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><p>As shown in Figure 3 this is the structure of Linked list , head holds the reference of first item in the list and tail holds reference of last item in the list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*Z84Oi3K8hWTVadhZ1hMkbw.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><p>As shown in Figure 4 memory structure of array and linked list and you can see if you have a reference of array you can access its element easily since it is stored contagious (meaning the second element of array is next to memory sequence) where as linked list element can be in any location, that’s why head hold the reference of first element which is oX10 and that element holds the reference of next element which is inoX12 address in memory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*V8XGYza2Vq176D590QAavw.png" /><figcaption><strong>Figure 4</strong></figcaption></figure><h3>push operations</h3><p>Adding a value at the front of the list is known as a push operation. This is also known as head-first insertion.</p><p>As shown in Figure 5 we did few things</p><ul><li>create Node class , that represent element in the list which has two property actual value and reference to new node</li><li>Then we create a Linked List class that has head represent first element in list and tail represent last element in list</li><li>On push operation we need to add element at first which means new item become head</li><li>New item next item will be the previous head we have</li><li>if tail is null means currently list is empty so first or newly added item is head and tail both</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvxKcrSmz43_haLGpXsFAQ.png" /><figcaption><strong>Figure 5</strong></figcaption></figure><p>if we wanted to get more info about the object being printed and, most importantly, in a human-readable way? For that, we have a great tool — the CustomStringConvertible protocol.</p><p>The description is required by the protocol and the string we compose in it will be printed in the console when using print() statement</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKjoag1rpCw8Nn2Dl23Bqw.png" /></figure><h3>append operations</h3><p>“ This is meant to add a value at the end of the list, and it is known as tail-end insertion.”</p><p>Like before,</p><ul><li>if the list is empty, you’ll need to update both head and tail to the new node. Since append on an empty list is functionally identical to push, you simply invoke push to do the work for you.</li><li>In all other cases, you simply create a new node after the tail node. Force unwrapping is guaranteed to succeed since you push in the isEmpty case with the above guard statement.</li><li>Since this is tail-end insertion, your new node is also the tail of the list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anloZC4F-xO5f5k6ZkCztQ.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><h3>node(at:)</h3><p>will try to retrieve a node in the list based on the given index. Since you can only access the nodes of the list from the head node, you’ll have to make iterative traversal</p><ol><li>You create a new reference to head and keep track of the current number of traversals.</li><li>Using a while loop, you move the reference down the list until you’ve reached the desired index. Empty lists or out-of-bounds indexes will result in a nil return value.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hto-8CCTuJcrP4jcDUnWJQ.png" /><figcaption><strong>Figure 7</strong></figcaption></figure><h3>insert(after:) operations</h3><p>This operation inserts a value at a particular place in the list, and requires two steps:</p><ol><li>Finding a particular node in the list.</li><li>Inserting the new node</li></ol><p>As shown in Figure 7 if we need to insert 3 after 2 we need to first find 2 and 2 → next will be inserted item and inserted item will be will point to previous 2 → next item</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*ShkqJjhB4CtsH0dn9Gvtjg.png" /><figcaption><strong>Figure 8</strong></figcaption></figure><ol><li>In the case where this method is called with the tail node, you’ll call the functionally equivalent append method. This will take care of updating tail.</li><li>Otherwise, you simply link up the new node with the rest of the list and return the new node.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WzOPEH51nVlsEOAOZAP1w.png" /><figcaption><strong>Figure 9</strong></figcaption></figure><h3>Performance analysis</h3><p>Whew! You’ve made good progress so far. To recap, you’ve implemented the three operations that add values to a linked list and a method to find a node at a particular index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5X58V7B2ZdtqWnF7P4rwA.png" /></figure><h3>pop operations</h3><p>Removing a value at the front of the list is often referred to as pop. This operation is almost as simple as push, so dive right in</p><ol><li>pop returns the value that was removed from the list. This value is optional, since it’s possible that the list is empty.</li><li>By moving the head down a node, you’ve effectively removed the first node of the list.</li><li>ARC will remove the old node from memory once the method finishes, since there will be no more references attached to it.</li><li>In the event that the list becomes empty, you set tail to nil.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMWU_ETMfrYOimSxYOPYmg.png" /><figcaption><strong>Figure 10</strong></figcaption></figure><h3>removeLast operations</h3><p>Removing the last node of the list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*-Wl6Gh0vkYRD1NL9RQkGSQ.png" /><figcaption><strong>Figure 11</strong></figcaption></figure><ol><li>If head is nil, there’s nothing to remove, so you return nil.</li><li>If the list only consists of one node, removeLast is functionally equivalent to pop. Since pop will handle updating the head and tail references, you’ll just delegate this work to it.</li><li>You keep searching for a next node until current.next is tail which means we reached to node 4</li><li>Since current is the second last node we make this as tail and make next to nil which ARC auto free memory</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3XBE9vtmcw0281eGWpp_A.png" /><figcaption><strong>Figure 12</strong></figcaption></figure><h3>remove(after:) operations</h3><p>The unlinking of the nodes occurs in the defer block. Special care needs to be taken if the removed node is the tail node, since the tail reference will need to be updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNF_6AyyBHtxQnkzQOef7w.png" /><figcaption><strong>Figure 13</strong></figcaption></figure><h3>Performance analysis</h3><p>You’ve hit another checkpoint! To recap, you’ve implemented the three operations that remove values from a linked list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZutzfsuDW3XBT35k-j7SgQ.png" /><figcaption><strong>Figure 14</strong></figcaption></figure><h3>Becoming a Swift collection</h3><p>I want to use my Linked list as for in loop and when i do and swift compiler give me error For-in loop requires ‘LinkedList&lt;Int&gt;’ to conform to ‘Sequence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRb-ScpyZ7tTyBehynLuFw.png" /><figcaption><strong>Figure 15</strong></figcaption></figure><h3>Conforming to the Sequence Protocol</h3><p>Making your own custom types conform to Sequence enables many useful operations, like for-in looping and the contains method, without much effort. To add Sequence conformance to your own custom type, add a makeIterator() method that returns an iterator.</p><p>Alternatively, if your type can act as its own iterator, implementing the requirements of the IteratorProtocol protocol and declaring conformance to both Sequence and IteratorProtocol are sufficient.</p><p>Here’s a definition of a Countdown sequence that serves as its own iterator. The makeIterator() method is provided as a default implementation.</p><p>As shown in <strong>Figure 16 </strong>we are using linked list items as for in loop , we just did few things</p><ul><li>Conform to Sequence, IteratorProtocol protocol</li><li>implement next() -&gt; Node&lt;Value&gt;? method</li><li>Note in next method we mutate head value and still after for in loop head reset</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VoXSMToN1hvOfxIJJbdEOA.png" /><figcaption><strong>Figure 16</strong></figcaption></figure><p>the example below we used the array’s contains(_:) method, which every sequence inherits from Sequence, instead of iterating manually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0mNuNzCr3LCd4JE-B2nw3w.png" /><figcaption><strong>Figure 17</strong></figcaption></figure><p>What if we want to access linked list using subscript notation for that we need to conform to Collection protocol</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgkWT7AbmJMaBX5Mawkuug.png" /><figcaption><strong>Figure 18</strong></figcaption></figure><h3>Conforming to the Collection Protocol</h3><p>If you create a custom sequence that can provide repeated access to its elements, make sure that its type conforms to the Collection protocol in order to give a more useful and more efficient interface for sequence and collection operations. To add Collection conformance to your type, you must declare at least the following requirements:</p><ul><li>The startIndex and endIndex properties</li><li>A subscript that provides at least read-only access to your type’s elements</li><li>The index(after:) method for advancing an index into your collection</li></ul><p>(In progress …………….. Just published beacuse this blog need <a href="https://ali-akhtar.medium.com/swift-new-concurrency-framework-part-3-701356819bb6">this</a> blog info )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4fcccba1fda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift New Concurrency Framework (Part 2)]]></title>
            <link>https://ali-akhtar.medium.com/swift-new-concurrency-framework-part-2-7004822b7860?source=rss-ec9cefb72e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/7004822b7860</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <dc:creator><![CDATA[Ali Akhtar]]></dc:creator>
            <pubDate>Tue, 10 May 2022 19:47:24 GMT</pubDate>
            <atom:updated>2022-05-10T19:47:24.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wm2-p7QpfxFQ7YkP.jpeg" /><figcaption><a href="https://developer.apple.com/news/?id=2o3euotz"><strong>https://developer.apple.com/news/?id=2o3euotz</strong></a></figcaption></figure><p>It is mandatory to read <a href="https://ali-akhtar.medium.com/swift-new-concurrency-framework-part-1-eac83c17dfb9">part1</a> before continue this , OR if you have idea how async/await basic implementation</p><blockquote><a href="https://thisdevbrain.com/how-to-use-async-await-with-ios-13/#:~:text=Apple%20released%20the%20beta%20version,watchOS%208%2C%20and%20tvOS%2015.">Apple released the beta version of Xcode 13.2. Besides the latest versions of the SDKs, it also brings backward compatibility for Swift’s new concurrency system. Until now, we could use async/await only with iOS 15, macOS Monterey, watchOS 8, and tvOS 15. Xcode 13.2 extends supported systems way back to iOS 13, macOS Catalina, watchOS 6, and tvOS 13. This is huge for developers as we still need to support earlier versions of the system. Let’s take a look at how to use it in practice.</a></blockquote><p>As shown in Figure 1 we created a simple generic Network Manager to perform network request just pass model you expect in response and it in return fill that model , the magic Codable do normally, You have situation like NetworkManager in written in third party framework and they are very lazy to adopt new things so you can’t change their code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnkotNPPXXLB-eGVnizZ_g.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><p>In Figure 2 you see how our code is using completion handler and we have minimum deployment is ios13 and we have Xcode 13.2, so our developers are very excited to use async-await because of it;s great benefits we saw in <a href="https://ali-akhtar.medium.com/swift-new-concurrency-framework-part-1-eac83c17dfb9">part1</a>. The only problem is we can’t change NetworkManger class .Inshort client want to use new SDK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XZr0FXV6vNDWpNeDM0d9w.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><h3>Continuations to convert completion handlers into async functions</h3><ul><li>Swift uses <em>continuations</em> to solve this problem, allowing us to create a bridge between older functions with completion handlers and newer async code.</li><li>As you can we have getFirstTodo older method that uses completion handler , we created async alternative firstTodo that internally calling our completion signature method and uses <em>continuations to make a bridge , In short we refactor with no major impact on our older code , it might possible some will call </em>getFirstTodo and new code will call firstTodo</li><li>Swift provides us with continuations, which are special objects we pass into the completion handlers as captured values. Once the completion handler fires, we can either return the finished value, throw an error, or send back a Result that can be handled elsewhere.</li><li>As you can see, starting a continuation is done using the withCheckedContinuation() function, which passes into itself the continuation we need to work with. It’s called a “checked” continuation because Swift checks that we’re using the continuation correctly, which means abiding by one very simple, very important rule: “<strong>Your continuation must be resumed exactly once. Not zero times, and not twice or more times — exactly once.:</strong></li><li>By using continuation you observe we can make async alternative of our completion block method code , now callers can use it using async/await syntax</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWEBjuIBI-6LTJjnJ6-Lrg.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><ul><li>When we call firstTodo async function , it internally call getFirstTodo which have completion block . We need to return the result from the callback back to the places awaiting calls to the async firstTodo function. Not only that, those callers are in a suspended state. We need to make sure to resume them at the right point in time and with the right data so that they can get on with the rest of their work.</li><li>In part1 we showed you how Swift and the system cooperate to take care of suspend and resuming async code for us. The question is how in this case suspend/resume process works</li><li>When the async version of firstTodo it then calls getFirstTodo which from network fetch todo. At some later time, Network calls the completion handler and passes the result . This situation looks almost identical to the one we previously showed you earlier when our AsynchronousFunctionOne function asked the system, not Network, to resume a suspended async function call. (This things is important here when we discuss continuation)</li><li>All that’s missing is a bridge to await the completion handler and resume with the getFirstTodos results.</li><li>This pattern comes up all the time, and it has a name: a continuation. : (methods that take completion blocks).</li><li>The caller of the method awaits the result of the function call and provides a closure to specify what to do next. When the function call completes, it calls the completion handler to resume whatever the caller wanted to do with the result. This kind of cooperative execution is exactly the way async functions in Swift work. <strong>return await withCheckedContinuation { [weak self] (continuation: CheckedContinuation&lt;Result&lt;ToDo, Error&gt; </strong>with this line it’s same like await we do but previous resume was done automatically , in our case with continuation the second link which is resume is to be done manually , Both case thread will suspened one or more time or never suspend A/C to system level</li><li>The withCheckedContinuation function lifts completion blocks without errors Swift functions. It has a counterpart called withCheckedThrowingContinuation for the situations where you know a function will throw an error. These functions are the way to gain access to a continuation value you <strong>can use to resume a suspended async function</strong>. <strong>This also builds the first part of the bridge by allowing us to await calls to </strong><strong>getFirstTodo.</strong></li><li>Let’s finish building the bridge. The continuation value provides a resume function into which we place the results from the completion handler. Not only that, but resume provides the missing link we need to unsuspend any calls awaiting the result of the persistentPosts function. And there, in one neat package, is our finished bridge from completion handlers to async functions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PInW6mIdmet7K1THyubCIw.png" /><figcaption><strong>Figure 4</strong></figcaption></figure><h3>Continuation Keep in Mind</h3><p>Continuations provide a powerful way to manually take control over the execution of an async function, but there are some things to keep in mind.</p><ul><li>Continuations have a simple but important contract. Resume must be called <strong>exactly once on every path</strong>. But don’t worry. Swift has your back here.</li><li>If the continuation is discarded without resume being called, the Swift runtime will log a warning since this will result in async calls never unsuspending as shown in Figure 5</li><li>If a continuation is resumed multiple times in the same function, however, this is a more serious error as it can corrupt program data. To combat this, the Swift runtime will detect attempts to call resume multiple times and will ensure a fatal error occurs at the second resumption point as shown in Figure 6</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkLxQINKAVrUA2rLqrgG4g.png" /><figcaption><strong>Figure 5</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bm0ZAasnljmTLZiWMEc6OA.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><ul><li>Many APIs are event driven. They provide delegate callbacks to notify our application at specific critical points and allow it to respond appropriately. In order to properly adopt async/await, we’ll have to store the continuation and resume it later.</li><li>As before, we create a checked continuation.Then we save it and kick off the work.To respect the API contract of checked continuations, we make sure to resume the active continuation, and finally nil it out so we’re protected from calling it more than once.</li><li>Always remember: the checked continuation value here represents the ability to manually resume any async calls to this API, so it must be called on all paths.</li><li>If your delegate API is called many times or not at all in certain circumstances, it is critical to resume any active continuations exactly once.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VY48UiZ5DUNg3HV2PwDvQ.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><h3>Recap await</h3><ul><li>await is where the magic happens. Whenever the program finds the await keywords, it has the option of suspending the function. It may or may not do so, and the decision is up to the system.</li><li>If the system does suspend the function, await will return control, not to the caller, but to the system. The system will then use the thread to perform other work until the suspended function is done. The statements below await will not be executed until it has finished. The system decides what’s important to execute, and at some point, it will return control back to you after it sees the awaited function has finished.</li><li>You can think of it as a traffic light. If you are driving down the road and you find a red light, chances are you will stop. But if it is 4 AM in the morning and there’s no cars coming you may just run it. ***</li></ul><blockquote><strong>What you need to understand about await is that, if it does choose to suspend, nothing below it will execute until the system tells it to, and the system will use the thread to do other work.</strong>Every call to an async function, must be marked as await.</blockquote><blockquote>One final important note about await: It’s not guaranteed that the same thread that executed the code above it is the same one that will execute the code below it <strong>(commonly called the <em>continuation</em>).</strong></blockquote><h3>Continuation Summary</h3><ul><li>A continuation is simply what happens after an async call. When you are using async/await, the continuation is easy to understand: Everything below an await call, is a continuation.</li><li>In this example, the keyword await will (may) trigger a data download task in a different thread. Everything underneath await (that is, starting on the line with a guard), is a <em>continuation</em>. on Code1</li><li>Continuations are not limited to the async/await APIs. When you are using closure-based async APIs, a continuation is everything called within your completion handlers.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33d7d60d84a40088d17715e7e5d179cf/href">https://medium.com/media/33d7d60d84a40088d17715e7e5d179cf/href</a></iframe><p>This is a closure version of the code above. Once again, the continuation starts at the guard. The main difference is the completion handler version has a flow that is harder to follow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06f816fca48005d9f8e181d135f2b6c6/href">https://medium.com/media/06f816fca48005d9f8e181d135f2b6c6/href</a></iframe><ul><li>Swift provides a few methods we can use to convert callback-based code into async/await: withCheckedContinuation and withCheckedThrowingContinuation. The difference between the two is the latter is used for code that throws errors. I call these methods <em>explicit continuations</em>.:</li><li>If you wanted to start your async/await migration with this method, the simplest way to do it would be by wrapping a call to downloadImageAndMetadata(for:imageNumber:completionHandler) inside the withCheckedThrowingContinuation method.</li><li>The magic behind this function occurs inside the withCheckedThrowingContinuation part. This function will give us a CheckedContinuation&lt;T, E&gt; where E: Error object that provides us with methods we need to call. In this example, the original version of downloadImageWithMetadata passes us a DetailedImage or an error, and we need to call the right resume method depending on what we get. If this method called us with a Result&lt;DetailedImage, Error&gt;, we could call .resume(with:) and pass it the result directly.</li><li>Continuations <strong>must be called exactly once</strong>, therefore there must be a continuation call within every branch of withCheckedThrowingContinuation. If you forget to call .resume, things could go awry. Luckily, Swift will let you know.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01cb545bb713f74657f07877ccc1d783/href">https://medium.com/media/01cb545bb713f74657f07877ccc1d783/href</a></iframe><h3>Continue With Our Todo</h3><p>As shown in <strong>Figure 7 </strong>we created withCheckedThrowingContinuation and now function throw error as well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4_OXpzE4t7KJGR9NlS7oA.png" /><figcaption><strong>Figure 7</strong></figcaption></figure><h3>Useful Links</h3><p><a href="https://www.andyibanez.com/posts/converting-closure-based-code-into-async-await-in-swift/">Converting closure-based code into async/await in Swift</a></p><p><a href="https://developer.apple.com/videos/play/wwdc2021/10132/?time=1957">https://developer.apple.com/videos/play/wwdc2021/10132/?time=1957</a></p><p><a href="https://www.hackingwithswift.com/swift/5.5/continuations">Continuations for interfacing async tasks with synchronous code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7004822b7860" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift New Concurrency Framework (Part 1)]]></title>
            <link>https://ali-akhtar.medium.com/swift-new-concurrency-framework-part-1-eac83c17dfb9?source=rss-ec9cefb72e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/eac83c17dfb9</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <dc:creator><![CDATA[Ali Akhtar]]></dc:creator>
            <pubDate>Sun, 08 May 2022 18:49:34 GMT</pubDate>
            <atom:updated>2022-05-08T18:49:34.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gfykEYyBVzsh03jj.jpeg" /><figcaption><a href="https://developer.apple.com/news/?id=2o3euotz"><strong>https://developer.apple.com/news/?id=2o3euotz</strong></a></figcaption></figure><h3>Synchronous / Asynchronous Function</h3><ul><li>In Synchronous function your thread is blocked and waiting for that function to be finish</li><li>In Asynchronous function your thread is free to do other work when it’s done it will notify you by calling it’s completion handler OR you call function and then in return function call you at some point , but it’s not blocking <strong>OR</strong> An asynchronous model allows multiple things to happen at the same time. When you start an action, your program continues to run. When the action finishes, the program is informed and gets access to the result (for example, the data read from disk)</li></ul><p>As shown in Figure 1 viewDidLoad starts on main thread Then it calls synchronousFunction until that function is executed completely main thread is busy on that function and you can see your thread is block , After that when synchronousFunction complete its execution then it call AsynchronousFunction and call all the synchronous statement util it DispatchQueue.global().asyncAfter(deadline: .now() + where it create another thread and return immediately and before calling closure it call print(“After”) and after sometime it execute internal statement of the DispatchQueue.global( closure which shows it don’t block the thread that is the reason it’s Asynchronous function and it’s completion mark with <strong>@escaping I</strong>n example of an escaping closure is the completion handler. Depending on its implementation, a completion handler is typically executed in the future. A length task completes long after it was initiated, which means that the closure escapes and outlives the function it was created in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdJOAs1EZ7txSV-VP5JlZQ.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><p>There is no problem with the callbacks :p until you have only one . As shown in Figure 2 we have a dependent nested async task which we perform using callbacks and you will find two problems</p><ol><li>Callbacks pyramid of doom</li><li>Control flow hell</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9Gz73AeCfNs3-rfXqH8jQ.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*atuL7HVSAE1uo9Q6.png" /><figcaption><strong>CallBack Hell</strong></figcaption></figure><h3>Async / Await in Swift</h3><p>As shown in Figure 3 we make code cleaner and <strong>easy to rea</strong>d , these are all async function since it is using new<strong> structured concurrency of swift </strong>you can think and debug like you are working on synchronous function which is very <strong>helpful for the debugging purpose</strong> No, more callBack hell. There are lots of things to discuss and understand here , let’s jump</p><ul><li>Apple introduced the concept of async/await in Swift 5.5 and announced it in the <a href="https://developer.apple.com/videos/play/wwdc2021/10132/">WWDC21 session</a>. <em>Please note that async/await is only available in Swift 5.5 and Xcode 13. So please make sure to download latest Xcode version before proceeding with this tutorial</em></li><li>Completion Handler, Delegate is <strong>Unstructured</strong> wheres as <strong>async/await</strong> is structured code why? async/await construct follows the concept of structured concurrency. Meaning, for any code written using async/await follows the structural sequential pattern unlike how closures work. For example, you might be calling a function passing the closure parameters. After calling the async function, the flow will continue or return. Once the async task is done, it will call closure in the form of a completion block. <strong>Here, the program flow and closure completion flow was called at different times breaking the structure, thus this model is called unstructured concurrency.Structured concurrency makes code easier to read, follow and understand</strong>. Thus, Apple is aiming at making code more readable by adopting the concept of async/await starting Swift 5.5.</li><li>When you mark the function async they keyword the keyword should go just before throws in the function signature or before arrow if function doesn’t throw</li><li>Await after it suspend itself quickly unblocking the thread , the thread is then free to do other work</li><li>You can see we used URLSession async function available, SDK’s has hundreds of thousands of awaitable methods available for your to use</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDIEoFwMZIsRCdyBfSNUUA.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><p>When you comment out Task you see this Error<strong> async’ call in a function that does not support concurrency</strong> which means viewDidLoad is not have async function in their method signature so it can’t use await . we cannot call it directly from synchronous code. We will wrap it into Task where it will execute parallelly. We will see in detail Task later part</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oChTWdYFpY3AHfcyI4ngVw.png" /><figcaption><strong>Figure 4</strong></figcaption></figure><h3><strong>+ve Point (Async / Await)</strong></h3><ul><li>Short code</li><li>Safer (see Use async/await with URLSession section)</li><li>structured code</li><li>Make better reflect what’s your intend</li><li>easier to read, follow and understand.</li><li>more readable</li><li>It makes your code linear, concise, and it supports native Swift error handling. (Use async/await with URLSession)</li></ul><h3>Synchronous Function Call</h3><ul><li>When you call a Synchronous function you hand control of the thread (which is main in our case) your function (viewDidLoad) running on over to that function (SynchronousFunctionOne). If it is a Synchronous function you are calling then thread will be fully occupy doing work on behalf of that function until it finishes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_emfLRsJIk54i7Hilem5Q.png" /><figcaption><strong>Figure 5</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrYPITyGdY6j_7ReQJc1Gw.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><h3>Async/Await Function Call (Asynchronous Structured Code)</h3><ul><li>Just like a normal function, when you call an async function (<strong>AsynchronousFunctionOne</strong>), you give control of the thread (Main Thread )to it.</li><li>Once it’s running, an async function can suspend. When it does, it gives up control of the thread. But rather than giving control back to your function, it instead gives control of the<strong> thread to the system.</strong> When that happens, your function (<strong>AsynchronousFunctionOne</strong>) is suspended too.</li><li>Question is when you can see the function can suspend when you see the word <strong>await so in our case </strong>try await URLSession.shared.data(from: url) at that point function can suspend, This is also known as suspension point , Note when the function is suspend , that thread is free to do other work. Further <strong>try</strong> <strong>await</strong> URLSession.shared.data(from: url) this line will create another background thread as well</li><li>Suspending is the function’s way of telling the system, “I know you have a lot of work to do. You decide what’s most important.” How cooperative is that? So once the function suspends itself, the system is free to use the thread to do other work. At some point, the system will decide that the most important work to be done is to continue running the async function that had suspended itself earlier. At that point, the system will resume it. That async function is then back in control of the thread and able to keep going about its work.</li><li>And if it wants, it can suspend itself again. In fact, it can suspend itself as many times as it needs to.</li><li>On the other hand, it may not need to suspend itself at all. While an async function may suspend, just because it’s marked async doesn’t necessarily mean that it will suspend. And by the same token, just because you see an “await” doesn’t mean the function will definitely suspend there. But eventually, whether without ever suspending or after resuming for the last time, the function will finish, handing control of the thread back to your function, along with a value or an error.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BlfVVg42V0oqacDvCW7Pvw.png" /><figcaption><strong>Figure 7</strong></figcaption></figure><ul><li>Let’s take another look at AsynchronousFunctionOne to see what can happen when it suspends.</li><li>When AsynchronousFunctionOne calls URLSession’s async data method, the data method <strong>stops executing on the thread</strong> in the special way that only async functions can: by suspending. It gives control of the thread to the system and asks the system to schedule the work for URLSession’s data method. Here thread is main so it will suspend main thread , Note most important that’s why I am iterating again and again suspend means main thread is free , firther more URLSession do network connection and everything in another thread internal to its implementation but why main thread is suspend since it is passed</li><li>On suspension point, the system is in control, and that work may not be started immediately. The thread can be used for other things instead. Let’s see how that might happen. Suppose that after AsynchronousFunctionOne has been called, the user taps a button which will upload some data. Say, for example, that they react to a post. Then the system is free to execute the work to post the user’s reaction before the previously queued-up work.</li><li>Once that late-breaking work has completed,<strong> URLSession’s data method may be resumed</strong>. Or <strong>the system might execute other work instead.</strong> Finally, once the data method finishes, it will return to AsynchronousFunctionOne. The fact that other work can be performed while a function is suspended is why Swift<strong> insists that you mark async calls with the await keyword. You need to be aware that the state of your app can change dramatically when your function suspends. we will cover details this point later why it is important</strong></li><li>Now, this is also true when you use completion handlers. But because you don’t have all the ceremony and indentation they entail in async/await code, the <strong>await keyword is how you notice that a block of code doesn’t execute as one transaction.</strong> The function may suspend, and other things may happen while it’s suspended between the lines of the function.</li><li>More than that, the function may resume onto an entirely different thread.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PctgST8gtcQYxsQ2VMnT7g.png" /><figcaption><strong>Figure 8</strong></figcaption></figure><h3>In short</h3><ul><li>when you mark a function async, you’re allowing it to suspend. And when a function suspends itself, it suspends its callers too. So its callers must be async as well. If not then we use Task as we did in viewDidLoad</li><li>To point out where in an async function it might suspend one or many times, the await keyword is used. (Called Suspension Point), Note it is possible that function may or may not suspend , also when. resume comes in a different thread</li><li>while an async function is suspended, the thread is not blocked. So the system is free to schedule other work. Even work that gets kicked off later can be executed first. That means your app’s state can change a great deal while the function is suspended. Finally, when an async function resumes, the results returned from the async function it called flow back into the original function, and execution continues right where it left off. You’ve seen how async/await works in Swift.</li></ul><h3>Use async/await with URLSession</h3><p>Networking is inherently asynchronous, and in iOS 15 and macOS Monterey apple introduced a set of new APIs in URLSession for you to take advantage of Swift concurrency features as we see in previous sections as well</p><p>In Figure 9 there is a code to download image from url . It’s using the completionHandler-based convenience method on URLSession. The code seems straightforward, and it worked in limited testing. However, it has at least three mistakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ul4bze8Sjys_KvxU7SSfSg.png" /><figcaption><strong>Figure 9</strong></figcaption></figure><ol><li>Let’s dive in. First, let’s follow the control flow. We create a data task and resume it. Then once the task is done, we jump into the completion handler, we check the response, create an image, and that’s where the control flow ends., we are jumping back and forth.</li><li>What about threading? It is surprisingly complex for this small piece of code. We have three different execution contexts in total. The outmost layer runs on whatever thread or queue of the caller, URLSessionTask completionHandler runs on session’s delegate queue, and the final completion handler runs on the main queue. Since the compiler cannot help us here, we have to use extreme caution to avoid any threading issues such as data races. Also noticed something wrong. The calls to the completionHandler are not consistently dispatched to the main queue. This could be a bug.</li><li>we are missing an early return here. The completionHandler can be called twice if we got an error. This could violate assumptions made by the caller. Finally, this might not be very obvious, but UIImage creation can fail. If the data is in an incorrect format, this UIImage initializer returns nil, so we would have called the completionHandler with both nil image and nil error. This is likely not expected. In Pros of Async/Await we write a point safe and you will see once we convert it into async-await code will be safer too</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FMinWMEITV-Q5fEylGMWA.png" /></figure><p>Now this is the new version using async/await. Wow, it’s so much simpler!</p><ul><li>The control flow is linear from top to bottom,</li><li>we know that everything in this function runs in the same concurrency context, so we no longer need to worry about threading issues. Here, we used the new async data method on URLSession. It suspends the current execution context without blocking, and it returns data and response on successful completion, or throws an error. We also used the throw keyword to throw errors when the response is unexpected. This allows the caller to catch and handle the error using Swift native error handling.</li><li>, the compiler would bark if we try to return an optional UIImage from this function, so it essentially forces us to handle nil correctly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRR92-BZXhW2dyfadxO95w.png" /></figure><p>Here are the signatures of the methods we just used to fetch data from the network. URLSession.data methods accept either a URL or a URLRequest. They are equivalent to existing data task convenience methods. Please refer to this to see <a href="https://developer.apple.com/videos/play/wwdc2021/10095/">video</a> of this WWDC talk</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ShUZDmAjQJMVAamKtL1mNQ.png" /></figure><h3>Useful Links</h3><ul><li><a href="https://developer.apple.com/videos/play/wwdc2021/10132/#">Meet async/await in Swift - WWDC21 - Videos - Apple Developer</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2021/10095/">Use async/await with URLSession - WWDC21 - Videos - Apple Developer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eac83c17dfb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UIKit Relative Frame Understanding]]></title>
            <link>https://ali-akhtar.medium.com/uikit-relative-frame-understanding-f88b272c77ef?source=rss-ec9cefb72e16------2</link>
            <guid isPermaLink="false">https://medium.com/p/f88b272c77ef</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ali Akhtar]]></dc:creator>
            <pubDate>Fri, 15 Apr 2022 20:45:11 GMT</pubDate>
            <atom:updated>2022-04-15T20:45:11.285Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Orange View</strong></p><p>In Figure 1 as you can see Orange View constraint from top 37 , height = 400 , leading and trailing = 0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVfEba4Al2zyPjnCxQIHew.png" /><figcaption><strong>Figure 1</strong></figcaption></figure><p>In Figure 4 you will see the globalFrame which is distance of that view with window if specify nil , so for orange view there is no logic at all , since orange view is same frame with parent and window.</p><p>For figure 3 you can understand midX , minX and maxX, middle of that view with parent or global frame which is window same from minX and maxX</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQKGFNGdpcwpstxYCY6qwQ.png" /><figcaption><strong>Figure 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGZr4q0uUK-C_DBKXtmEyg.png" /><figcaption><strong>Figure 3</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHoqkHbmYqc4__KdVTa1dQ.png" /><figcaption><strong>Figure 4</strong></figcaption></figure><p><strong>Green View</strong></p><p>In Figure 5 as you can see Green View constraint</p><p>topToSuperView → topToOrangeView → 16</p><p>bottomToBlueView → 16</p><p>height → 100</p><p>leading and trailing to superView → leading and trailing to orangeView → 16</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwLqdT-JfiFUmW7rE2FUqw.png" /><figcaption><strong>Figure 5</strong></figcaption></figure><p>Figure 6, 7 you can observe</p><p>frame from parent it gives the value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTWe96fevfPD7mXpiZsneQ.png" /><figcaption><strong>Figure 6</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8awOGnHnnSSx1BBmqpABA.png" /><figcaption><strong>Figure 7</strong></figcaption></figure><p>For global frame you can see , just consider window as parent and neglect orange view so from window x = 16 , y = 128 + 16 = 144 is the only difference since for x perceptive parent view act as window but for y things change</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vm4x0EVxfYuFhObPNbIGQ.png" /><figcaption><strong>Figure 8</strong></figcaption></figure><p><strong>Red View</strong></p><p>16 points to parent which is green view from everywhere 4 side simple</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jy4AG31_KfOxdRiT5vOenA.png" /><figcaption><strong>Figure 9</strong></figcaption></figure><p>Green View as parent Normal Flow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cJxzvk9BmfLVZFW6PnQKw.png" /><figcaption><strong>Figure 10</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgpGEbMoLOk_KkXQO7J4xQ.png" /><figcaption><strong>Figure 11</strong></figcaption></figure><p>Global Frame (Window as parent View)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWY3Ct3UFATa8JkeuieRZA.png" /><figcaption><strong>Figure 12</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9INrKVwevbOrxyNtPKnoQ.png" /><figcaption><strong>Figure 13</strong></figcaption></figure><h3>White View</h3><p>16 points to parent which is red view from everywhere 4 sides simple</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdZQmymQ3eBD687NpCsgVQ.png" /></figure><p>Red View as parent Normal Flow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ql9VzqzYPGgMxl2ix08cnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYFAgZ_JoGWvypVJaUxiDg.png" /></figure><p>Window as parent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IWtcXvUe-lK5FG-xiJztA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZgPyoHkoPbya3TGSyZuXQ.png" /></figure><p>Now this is very important <strong>White View</strong> with Parent <strong>GreenView instead of RedView , note we are only getting frame in respect to GreenView we are not changing parent view</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzBtmq2O3gpUS2mCklQZhg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f88b272c77ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>