<?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 Dimitar Stefanovski on Medium]]></title>
        <description><![CDATA[Stories by Dimitar Stefanovski on Medium]]></description>
        <link>https://medium.com/@dimitarstefanovski?source=rss-5c13da421b7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AD0p5b9neUFwWXNXcHbK8w.jpeg</url>
            <title>Stories by Dimitar Stefanovski on Medium</title>
            <link>https://medium.com/@dimitarstefanovski?source=rss-5c13da421b7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:24:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dimitarstefanovski/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[Creating an iOS Widget for your Wallet app]]></title>
            <link>https://medium.com/@dimitarstefanovski/creating-an-ios-widget-for-your-wallet-app-abe303db9d73?source=rss-5c13da421b7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/abe303db9d73</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[widgetkit]]></category>
            <dc:creator><![CDATA[Dimitar Stefanovski]]></dc:creator>
            <pubDate>Tue, 08 Sep 2020 15:54:45 GMT</pubDate>
            <atom:updated>2020-09-09T07:49:59.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*kHX22AgOB_-eny-8VSbcOw.png" /><figcaption>iPhone X Actual Screenshots</figcaption></figure><h3>What is a Widget?</h3><p>Widgets are a powerful extension for your iPhone, iPad and Mac apps and is a perfect way to extend and personalize your iPhone home screen with new visual functionality. We shouldn’t need to interact or do anything more than take a quick peek to get most value out of our widget. The content of the widget is in the <strong>focus</strong>, and we don’t need to tap any buttons or even spend time trying to figure out a complicated UI (widgets are not mini apps). Widgets will be available in iOS 14 or later and macOS 11 and later.</p><h3>A closer look at widgets</h3><p>A widget is just a SwiftUI view, so it’s the same declarative code that generates gorgeous native view on iOS, iPadOS and macOS. Widgets does not support animations or custom interactions but does support deep linking with the help of the Link modifier.</p><h3>Start building the Wallet widget</h3><p>The main goal of this article is to properly configure the wallet widget and the main focus will be on connecting the SwiftUI view to the widget configuration. The details of building the wallet SwiftUI view will be not covered by this article.</p><h3>Idea and UI design inspiration</h3><p>First, we need a prototype to know what we are going to be building, so for that purpose I have already designed the look of the widgets in Figma.</p><p>We have all 3 sizes of the widget pre-built:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*isW-_-wibvkPTKFIjDP8CQ.png" /><figcaption>Small</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*XyXseaPrpqg1deF3E2MGhw.png" /><figcaption>Medium</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*oSCZhQ3zyLwAsv2dZ10zOQ.png" /><figcaption>Large</figcaption></figure><h3>Creating a widget target</h3><p>To start creating the widget for our iOS app we need to create a new target. For that we need to create new project for our wallet app and add the new widget target:</p><p>File -&gt; New -&gt; Target</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*w9t1hyX90g1Swsky6-TnEg.png" /><figcaption>File -&gt; New -&gt; Target</figcaption></figure><p>Search for the Widget extension and press Next</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*mf4TtOlYYHTxP4vRfw2TYw.png" /></figure><p>Enter the name of the new target, deselect the intent configuration option as for now we will only work with the static configuration for our widget. In the next chapter we will add intent configuration for our wallet widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*bIrve9HHLhspG8fE4Atr2A.png" /></figure><p>Press finish.</p><p>Activate the target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*GfjLGgnmouYnx5Qf25J6wA.png" /></figure><h3>Using the predesigned SwiftUI wallet widget view components</h3><p>We are going to use predesigned SwiftUI views for this tutorial. For that purpose, we can checkout the <a href="https://github.com/dimebt/wallet-widget">repository</a> and drag the files that are in the Shared Components folder into our newly created Xcode project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*C49kdLVTc7StU4vj2d_1bA.png" /></figure><p>Don’t forget to select the Widget target in the target membership window:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*xYTcd4S3zsuWGyu5iW5WxA.png" /></figure><h3>Setting up the Widget Configuration</h3><p>The widget extension template provides an initial widget struct implementation that conforms to the Widget protocol. In the body of the widget we determine whether or not the widget has user-configurable properties. Widgets can be configured in one of two configuration options that are available:</p><ul><li><strong>StaticConfiguration</strong>: This configuration is used on a widgets that has no custom user-configurable properties. Example for this type of static configuration would be a news widget that only shows a trending headline.</li><li><strong>IntentConfiguration</strong>: Configuration that is used on widgets that have user-configurable properties to select from. The properties list is static or dynamically generated. Example widgets for this kind of configuration would be whether app widget that needs a zip or postal code for a city or game widget that needs selection of game hero character from the game. We use SiriKit custom intent to define these configuration properties.</li></ul><p>Previously we have not selected the <strong>Include Configuration Intent</strong> checkbox and by default the StaticConfiguration for our wallet widget is used.</p><p>To initialize the configuration, we have to supply the following information:</p><ul><li>Kind: A string that identifies the widget. Can be any string that describes of what the widget represents.</li><li>Provider: An object conforming to TimelineProvider that produces the timeline entries and tells the WidgetKit when to render (update) the widget on the screen.</li><li>Content Closure: A closure that contains the SwiftUI view. WidgetKit invokes this to render the widget’s content passing the TimelineEntry parameter from the provider.</li></ul><p>To provide additional configuration details, including the display name, a widget description and the families that the widget supports we can use the modifiers on the widget configuration. For the following wallet widget, we use the configuration setup:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92fcc1c3d8e8e089fd7f55c8d2c389f4/href">https://medium.com/media/92fcc1c3d8e8e089fd7f55c8d2c389f4/href</a></iframe><h3>Supported families</h3><p>As we see in the Shared Components folder there are 3 SwiftUI views (WWidgetSmall.swift, WWidgetMedium.swift, WWidgetLarge.swift) and they corresponds to each widget size family (.<strong><em>systemSmall</em></strong>, .<strong><em>systemMedium</em></strong>, .<strong><em>systemLarge</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-67Kk9epfFRIMt4ygAvJYg.png" /><figcaption>Supported widget families</figcaption></figure><p>To support all widget sizes we have to tell the system that we want to use all the sizes families and for that we have to add .supportedFamilies modifier and pass the array of supported system sizes to the WalletWidget struct configuration.</p><p>WidgetKit also provide us with the widgetFamily environment object so that we can use that to switch over the provided families and decide which size widget we want to render:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd1b6d705c0d77dfbdd6f2671d58788b/href">https://medium.com/media/bd1b6d705c0d77dfbdd6f2671d58788b/href</a></iframe><h3>Timeline provider</h3><p>The engine of the Widget is the TimelineProvider protocol which is responsible for <strong>when</strong> to render the UI display of the widget. At some time WidgetKit will request a timeline from the TimelineProvider. Timeline is basically an array of objects conforming to the TimelineEntry protocol and each timeline entry must consist of a date property and any other additional properties for displaying the widget.</p><p>WidgetKit will asks for timeline entries in one of two ways:</p><ul><li>A single immediate snapshot, representing the widget’s current state.</li><li>An array of entries, including the current moment and, if known, any future dates when the widget’s state will change.</li></ul><p>WidgetKit will make a snapshot request when displaying the widget in transient situations, such as when the user is adding the widget and previewing it from the widget gallery. WidgetKit provides a context parameter that includes details about how to render the widget including whether it’s a preview for the widget gallery and if context.isPreview is true, the widget appears in the widget gallery and requires a quick response from the provider. If the required information you need to generate the snapshot is not available immediately or requires additional time to load, use sample data instead.</p><p>For the snapshot entry for our wallet widget we will return sample data that is why we will not pass any additional parameter while crating the WalletWidgetEntry object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58a2bcc5b496347d3c3d53687b5e2771/href">https://medium.com/media/58a2bcc5b496347d3c3d53687b5e2771/href</a></iframe><p>WidgetKit will make the timeline request after we add the widget from the widget gallery. Because the widget extension is not always running, WidgetKit needs to know when this extension will be activated and update the display of the widget. For that purpose, the timeline provider generates an array of timeline entries with the exact time when we want to update the widget. The following example shows a timeline generated for the wallet widget, notice that we update the widget every 1 minute, this can be configured depending of the logic and the requirements of the widget we built, but for demonstration purposes we will update the widget on each minute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25fd26fb56b9baab16e36654bf815e3e/href">https://medium.com/media/25fd26fb56b9baab16e36654bf815e3e/href</a></iframe><p>When creating the timeline, before we return the timeline into the completion handler, we should also specify a TimelineReloadPolicy parameter. With this parameter we control when WidgetKit will request a new timeline from the provider. The default behavior is to use .atEnd this will request a new timeline after the date specified in the last entry in the current timeline. For the wallet widget the only requirement we want is to fetch the latest changes from a server on every minute and for triggering an update we will use the .after(_ date: ) reload policy parameter and specify the next update date. The following example shows how the widget provider generates a timeline consisting of single entry and a reload policy to request a new timeline in 1 minute.</p><p>Each widget receives a limited number of refreshes every day. The system decides how many refreshes a widget receives, and several factors are responsible for this such as whether the app is running in the background or foreground, how frequently the widget is shown onscreen, and what types of activities the app engages in.</p><p><strong>Please note that refresh limit is not the same when debugging your widget in Xcode, so please verify your widget behaves correctly outside the Xcode simulators and test the widget on a real physical device</strong>.</p><h3>Displaying a placeholder for the Wallet Widget</h3><p>When the widget is first time shown on the screen WidgetKit renders It as a placeholder view. A placeholder view displays a generic representation of the widget, giving the user a general idea how of how the widget will look. This placeholder view will basically contain the skeleton components to inform the user that something is happening and prepare them for the actual content they are waiting.</p><ul><li>Small size representation of the placeholder wallet widget view</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/101/1*jwwEfIL7KlL7SmDaXxc9Cg.png" /><figcaption>Small size placeholder</figcaption></figure><ul><li>Medium size representation of the placeholder wallet widget view</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*6qmOTTd6FATOs6Aon1oD6A.png" /><figcaption>Medium size placeholder</figcaption></figure><ul><li>Large size representation of the placeholder wallet widget view</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*RlMvyIictxipDW7XMgPzmQ.png" /><figcaption>Large size placeholder</figcaption></figure><p>For implementing the placeholder view WidgetKit calls placeholder(in: ) to request an entry representing the widget’s placeholder configuration. For the wallet widget would implement this method like follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c562cb788860d85c72733b91ea73aecc/href">https://medium.com/media/c562cb788860d85c72733b91ea73aecc/href</a></iframe><h3>User interaction and deep linking with the app</h3><p>As I mention at the beginning the widgets are not mini-apps and they not support custom interactions. This means every widget family has its different interaction guidelines we have to follow. When user interacts with the widget, the system launches the app to handle the request. The widget can be associated with a URL link using the widgetURL API modifier to inform the app what content to display. To configure custom URLs in your widget:</p><ul><li>For widget families .systemSmall, add the widgetURL(_:) view modifier to a view in your widget view hierarchy. This URL modifier can also be used in other widget families that you want only to support single tap target, so the entire widget is a tap target and will navigate the user directly into the app.</li><li>For widgets using the .systemMedium or .systemLarge, add one or more Link controls to your widget’s view hierarchy to support multiple tap targets.</li></ul><p>In our wallet widget example, we list 2 transactions on the medium size widget and 3 transactions on the large size widget, for that reason we will wrap each transaction with a Link control. Each Link control would specify the URL with a stringId parameter for the specific transaction to display:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e544e799bcdc050cb93b25f86fb83280/href">https://medium.com/media/e544e799bcdc050cb93b25f86fb83280/href</a></iframe><p>When the widget receives an interaction, the system activates the containing app and passes the URL to onOpenURL(perform:), application(_:open:options) or application(_:open:), depending of the life cycle your app uses. In our case we use SwiftUI and when an interaction is received it will be resolved with the onOpenURL(perform:) handler (modifier on the view) the id of the transaction will processed and a preview of that transaction will be showed in the app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0a86b4d333a68cbd7f79bf842df32ff/href">https://medium.com/media/a0a86b4d333a68cbd7f79bf842df32ff/href</a></iframe><h3>Conclusion</h3><p>Widgets are a great way for your users to quickly get the information they need and interact with your app. Your widgets always stay up to date, so users have the latest information at a glance. When they need more details, your widget takes them directly to the appropriate place in your app.</p><p>WidgetKit is a huge framework and in this tutorial, I have only covered the basic setup of the widget. Anytime you can download the example code on the <a href="https://github.com/dimebt/wallet-widget">repository</a> and test it on your machine. For any question you can contact me on email <a href="/service/mailto:dimitar.stefanovski@netcetera.com">dimitar.stefanovski@netcetera.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abe303db9d73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Downloading images in Swift using PromiseKit and Alamofire]]></title>
            <link>https://medium.com/@dimitarstefanovski/downloading-images-in-swift-using-promisekit-and-alamofire-65a42593814d?source=rss-5c13da421b7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/65a42593814d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[promisekit]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Dimitar Stefanovski]]></dc:creator>
            <pubDate>Thu, 07 Feb 2019 13:46:58 GMT</pubDate>
            <atom:updated>2019-02-07T13:48:12.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AY95K6FLeDhBe6al" /><figcaption>Photo by <a href="https://unsplash.com/@rawpixel?utm_source=medium&amp;utm_medium=referral">rawpixel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem</h3><p>Networking code can get really messy if we have to download some content from a remote location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*L4lJotHHCXe4b1wuOyv4DA.gif" /><figcaption>Downloading set of 40 photos and representing it to a collection view</figcaption></figure><p>First we have to know the path <em>(URL) </em>from where we want to download the content <em>(in our case that would be a photo)</em>. Second, probably that location or path will be written in some REST API endpoint request and after we process that JSON data response we have to start downloading the image and at last we have to update our UI.</p><p>All of this have to be done on a background thread because we do not want to block the main thread, and of course we want our app to stay responsive.</p><p>Best solution for this types of problems is using asynchronous programming and if we want our code to look very clean and tidy <strong>PromiseKit</strong> is the best choice. If you are new to asynchronous programming please check my previous post about <a href="https://medium.com/p/4bbb9e40f7cc">How to use PromiseKit for Swift</a>.</p><p>Next we’ll install <strong><em>PromiseKit</em></strong> and <strong><em>Alamofire </em></strong>library for networking requests using CocoaPods dependency manager. For installing the libraries with other dependency managers please visit the official documentation of PromiseKit <a href="https://github.com/mxcl/PromiseKit">https://github.com/mxcl/PromiseKit</a> and Alamofire <a href="https://github.com/Alamofire/Alamofire">https://github.com/Alamofire/Alamofire</a>.</p><h3><strong>Installing PromiseKit and Alamofire with CocoaPods</strong></h3><p>If you haven’t installed CocoaPods yet this is the time to do it. Go to the terminal app and write:</p><pre>$ sudo gem install cocoapods</pre><p>For details about using the CocoaPods dependency manager please visit official site <a href="https://cocoapods.org/">https://cocoapods.org/</a>.</p><p>Create new Xcode project (Single View Application) and in the directory of the project create new podfile using the command pod init.</p><p>Open the podfile and add the PromiseKit and Alamofire dependency libraries:</p><pre>target &#39;YourProjectTarget&#39; do<br>use dynamic frameworks<br>  use_frameworks!</pre><pre>  pod &#39;PromiseKit&#39;<br>  pod &#39;Alamofire&#39;</pre><pre>end</pre><p>Save the podfile and at this point you can install the libraries using the pod install command in the terminal:</p><pre>$ pod install</pre><p>From now you have to open the newly created workspace file <strong>.xcworkspace</strong> instead of <strong>.xcodeproj. </strong>That’s it, now we are ready using PromiseKit and Alamofire in our project.</p><h3>Real world example</h3><p>In this tutorial we’ll download set of photos from a remote location. The url’s of the photos we assume that will be written in some REST API endpoint and for the purpose of this example we’ll use placeholder API <a href="https://jsonplaceholder.typicode.com/photos">https://jsonplaceholder.typicode.com/photos</a> that has url’s for 5000 photos. Downloading the photos can take some time so we’ll show a preloading animation with activityIndicator component and hide it when downloading has finished. We will not persist the photos, they will be stored in a temporary array [UIImage]. For displaying the photos i’m using UICollectionView but you are free to use any visual component for displaying.</p><p>Steps to take:</p><ol><li>Show preloading animation</li><li>Fetch and serialize json response</li><li>Download photos</li><li>Hide preloading animation and update the UI</li></ol><p>The response form the API request is in the following JSON format:</p><pre>[<br>  {<br>    &quot;albumId&quot;: 1,<br>    &quot;id&quot;: 1,<br>    &quot;title&quot;: &quot;accusamus beatae ad facilis cum similique qui sunt&quot;,<br>    &quot;url&quot;: &quot;https://via.placeholder.com/600/92c952&quot;,<br>    &quot;thumbnailUrl&quot;: &quot;https://via.placeholder.com/150/92c952&quot;<br>  },<br>  {<br>    &quot;albumId&quot;: 1,<br>    &quot;id&quot;: 2,<br>    &quot;title&quot;: &quot;reprehenderit est deserunt velit ipsam&quot;,<br>    &quot;url&quot;: &quot;https://via.placeholder.com/600/771796&quot;,<br>    &quot;thumbnailUrl&quot;: &quot;https://via.placeholder.com/150/771796&quot;<br>  },<br>  ...<br>]</pre><p>With <strong>Alamofire</strong> and with a little help of the <strong>Codable</strong> protocol in Swift we’ll convert the <em>json</em> response in array of Photo objects. First let’s define the <strong>Model</strong> object <strong><em>(struct </em></strong><strong><em>Photo)</em></strong>:</p><pre>struct Photo: Codable {<br>    let albumId: Int<br>    let id: Int<br>    let title: String<br>    let url: String<br>    let thumbnailUrl: String<br>}</pre><p>If we write this code in one function, that will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a228327e7cebf9cb553addc6ee471f90/href">https://medium.com/media/a228327e7cebf9cb553addc6ee471f90/href</a></iframe><p>How can we avoid the nesting of the code? How can we separate the concerns in different code blocks?</p><p>Next i will show you how to wrap the code in separate functions with the help of promises.</p><h3>Wrapping functions with promises 🌮</h3><p><strong>Promise </strong>is a generic way of structuring code that could take long time to run, and might succeed or fail. The seal object that the Promise initializer provides to you defines many methods for handling completion handlers. A promise has to have fulfill and reject methods defined for the promise to be valid. The general syntax of a promise function is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/788c3ab3835b395b21a4abbc1ced8a14/href">https://medium.com/media/788c3ab3835b395b21a4abbc1ced8a14/href</a></iframe><p>First function we will wrap is the Alamofire request function. The new function will contain the same code, plus the code i have added for error handling and will return a Promise of type [Photo]:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a8698e79223c98664246195f2a58289/href">https://medium.com/media/8a8698e79223c98664246195f2a58289/href</a></iframe><p>After we have fetched the json data and converted it to [Photo] next function that we’ll be creating and wrapping is for the downloading the images from the url’s in the [Photo] object. For that purpose the next function will require a single argument of type [Photo] and return a promise with the array of images Promise&lt;[UIImage]&gt;:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f12bb670d5ee74779929da920c0f9c5/href">https://medium.com/media/1f12bb670d5ee74779929da920c0f9c5/href</a></iframe><h3>Using the promise functions</h3><p>Now we have our promise functions ready for using in our application but wait…</p><p>What is the order of completion handlers? How can we chain promise functions?</p><p>The goal in this example is to download the photos and present them in a UICollectionView. The steps we’ll take are in order:</p><ol><li>Show preloading animation</li><li>Fetch and serialize json response</li><li>Download photos</li><li>Hide preloading animation and update the UI</li></ol><p>This is the typical chain of functions that we have to take, and with the PromiseKit syntax this is so easy and readable. Because fetching the json response and downloading images will take some time we’ll push these functions to run on a background queue. Write this code in the viewDidLoad() method in your UIViewController class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f70ddda3fa11f791716a6897e4b50e/href">https://medium.com/media/a4f70ddda3fa11f791716a6897e4b50e/href</a></iframe><p>firstly {} closure is just a syntactical sugar for starting a typical promise chain and making the code more readable. We pass the first function showLoader() in this closure.</p><p>then {} closure is using for structuring the completion handlers and in this closure we pass the second function fetchJSON(). Also the then block is executing on the main queue by default, but in our case we want our code to be executed on the background queue, because of that we’ll supply the DispatchQueue via the on: parameter of the then(on: DispatchQueue) method. Then the PromiseKit performs the then block on provided queue.</p><p>In the next then we pass the third function downloadPhotos(photos: [Photo]), and we pass the Promise of type [Photo] as an argument from the previous then.</p><p>If you are questioning what is this code for Array(photos.prefix(40)), it’s just limiting the array of [Photo]’s to the first 40 objects because we do not want to download all 5000 photos.</p><p>done closure is same as then with a difference that you can’t return a promise from this block. We’ll add done closure to the chain, which will execute on the main queue when the downloadPhotos promise completes. In this block we will add the code for updating the user interface (hiding the activityIndicator and reloading the UICollectionView).</p><p>catch closure is place where error handling take place. If any of the promise fails to execute then all promise chain fails.</p><h3>Conclusion</h3><p>Asynchronous programming in iOS can be a pain 🤕 for a beginner programmer especially if you are not familiar with callbacks. A lot of nesting of function can occur and that leads to the famous callback hell or spaghetti code 🤷‍♂️. This can be avoided using appropriate techniques and libraries available at the moment.</p><p>One of the solution is using futures or promises and there are many implementation for promises in Swift, one of them is the popular <strong>PromiseKit </strong>library for Swift and ObjC.</p><p>PromiseKit let you write code as series of actions based on events and let your code look clean and beautiful. Promises allows us to control the whole asynchronous background process with his powerful closure syntax for chaining multiple async functions. For more information about using PromiseKit library please visit the official GitHub <a href="https://github.com/mxcl/PromiseKit">page</a>.</p><p>You can download the complete project code from my GitHub <a href="https://github.com/dimebt/PromiseKitExample">repository</a>.</p><p>I hope my example code helped you for better understanding of the PromiseKit library and if you have any suggestions and comments feel free to post them below. 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65a42593814d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use PromiseKit for Swift]]></title>
            <link>https://medium.com/@dimitarstefanovski/how-to-use-promisekit-for-swift-4bbb9e40f7cc?source=rss-5c13da421b7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bbb9e40f7cc</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[promisekit]]></category>
            <dc:creator><![CDATA[Dimitar Stefanovski]]></dc:creator>
            <pubDate>Thu, 07 Feb 2019 13:44:11 GMT</pubDate>
            <atom:updated>2019-02-07T14:20:52.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e5A6y_YTrimJGSrJ" /><figcaption>Photo by <a href="https://unsplash.com/@daniel_von_appen?utm_source=medium&amp;utm_medium=referral">Daniel von Appen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>PromiseKit is a popular third-party library for Swift and Objective-C programming language, and many developers are using this library to simplify the asynchronous tasks they have in their apps. Promises allows us to control the whole asynchronous background process with his powerful closure syntax for chaining multiple async functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHnNCDcWvPxfihd8jv_d7A.png" /></figure><h3>What is a promise?</h3><p><strong>Promise </strong>is a generic way of structuring code that could take long time to run, and might succeed or fail, or in other words a <strong>Promise </strong>is a functional abstraction of a fail-able asynchronous operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*GiSA59aSeenu8hdJTg_aAA.gif" /><figcaption>Waiting for a async function</figcaption></figure><h3>Where it is using?</h3><p>One of the main reasons for using Promises in our app is when we have multiple callback functions in our code. We all know that async functions will execute simultaneously right away but we don’t know when and who of the functions will finish first. What if we want to change the order and priority of the functions or we want one function to call after another has finished (chaining of async functions)?</p><p>Are you familiar with this code?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/582bc5554596fde7247d3a6cd0a1bbc0/href">https://medium.com/media/582bc5554596fde7247d3a6cd0a1bbc0/href</a></iframe><p>In the example code we have three nested functions that gets called one after another. First function <strong><em>func fetchJSON(fromURL: , completion:) </em></strong>returns JSON data, then we pass that JSON data into the second function to fetch specific info for a user <strong><em>func fetchUserData(for username:, completion:)</em></strong> and after that we call third function to login the current user <strong><em>func loginUser(user: , completion:)</em></strong></p><p>This is called a callback hell or pyramid of doom 🔥. This is not clean code and if you want to write clean structured code then <strong>Promises </strong>are the best choice for this type of problems, and in the next section I will explain the common promise patterns, how to create a promise and how to chain multiple promises.</p><h3>How to create a <strong>Promise</strong></h3><p>Let’s see the first fetch function from the above code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1720b3408cc94e59e92d47bb38e5a2b2/href">https://medium.com/media/1720b3408cc94e59e92d47bb38e5a2b2/href</a></iframe><p>Assuming that you have already installed the PromiseKit library and included in your project, how can we wrap this function to return a promise?</p><p>It’s simple …</p><p>We create another function promiseFetchJSON() -&gt; Promise&lt;[String: Any]&gt; that returns a Promise of generic type &lt;T&gt;, in our case because we want to fetch some JSON data the return type will be of type &lt;[String: Any]&gt;. In the body of the function we will call the fetchJSON() with the same functionality:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83261bc011650e4ee5b0614f886624c3/href">https://medium.com/media/83261bc011650e4ee5b0614f886624c3/href</a></iframe><p>Now you are wondering what is the seal object? The seal object that the Promise initializer provides to you defines many methods for handling completion handlers.</p><p>A promise has to have fulfill and reject methods defined for the promise to be valid. Next we will convert the other functions to return a promise:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a77f365b2b9b62c8c9e169ba6bbc1896/href">https://medium.com/media/a77f365b2b9b62c8c9e169ba6bbc1896/href</a></iframe><p>We have successfully wrapped all three functions to return a Promise, next we’ll see how we can use this new functions in our code.</p><h3>Using Promises</h3><p>Main purpose of Promises are chaining them together in a structural manner.</p><p>Here is a typical promise chain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1def62c90e867de7bdca6e276981b405/href">https://medium.com/media/1def62c90e867de7bdca6e276981b405/href</a></iframe><p>firstly is just a syntax to make code more readable and in this closure we pass the first promise function promise1().</p><p>then is another way to structure completion handlers that help us to easy understand asynchronous operations. <strong>If we return a </strong><strong>promise in a </strong><strong>then closure, then the next </strong><strong>then waits on that promise before continuing. </strong>If one of the promises fails to resolve then the whole promise chain fails.</p><p>The chain ends in the done closure and that means that all of the promises are fulfilled successfully.</p><p>Phew… a lot of then’s</p><p>Finally we can use this syntax to wrap up our custom Promise functions and chain them together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95db4dc137fc68cdaad3d86eca3387d1/href">https://medium.com/media/95db4dc137fc68cdaad3d86eca3387d1/href</a></iframe><p>Look how clean this is compared to the nested functions above. With the power of the PromiseKit syntax we have refactored the code for more readability.</p><h3>Conclusion</h3><p>Asynchronous programming in iOS can be a pain 🤕 for a beginner programmer especially if you are not familiar with callbacks. A lot of nesting of function can occur and that leads to the famous callback hell or spaghetti code 🤷‍♂️. This can be avoided using appropriate techniques and libraries that are available at the moment.</p><p>One of the solution is using promises and there are many implementation for promises in Swift, one of them is the popular <strong>PromiseKit </strong>library for Swift and ObjC. PromiseKit let you write code as series of actions based on events and let your code look clean and beautiful. Promises allows us to control the whole asynchronous background process with his powerful closure syntax for chaining multiple async functions. For more information about using PromiseKit library please visit the official GitHub <a href="https://github.com/mxcl/PromiseKit">page</a>.</p><p>I hope my code demonstration helped you for better understanding of the PromiseKit library and if you have any suggestions and comments feel free to post them below. 👏</p><p>If you are interested to see a real world example where Promises can be used please visit my post about <a href="https://medium.com/p/65a42593814d">Downloading images in Swift using PromiseKit and Alamofire</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bbb9e40f7cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>