<?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 john raymund catahay on Medium]]></title>
        <description><![CDATA[Stories by john raymund catahay on Medium]]></description>
        <link>https://medium.com/@raymund.cat?source=rss-c2605a55a531------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HoNTyb2eTwCYbalBcCnkTw.png</url>
            <title>Stories by john raymund catahay on Medium</title>
            <link>https://medium.com/@raymund.cat?source=rss-c2605a55a531------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 08:49:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raymund.cat/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[TabBar Items with Swift Enums]]></title>
            <link>https://medium.com/hackernoon/tabbar-items-with-swift-enums-c0e37be8ae21?source=rss-c2605a55a531------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0e37be8ae21</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[john raymund catahay]]></dc:creator>
            <pubDate>Sat, 25 Nov 2017 21:12:46 GMT</pubDate>
            <atom:updated>2019-05-17T10:50:36.217Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick tip on managing your child ViewControllers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IdqxCGYC4aLP81mPr3qOlg.jpeg" /></figure><p>Tabbed Navigations is pretty convenient and fun in iOS. Thanks to the native UITabBarController, a subclass of UIViewController, it doesn’t really need not much setting up other than its child ViewControllers.</p><p>But after that, admittedly, we do still find ourselves in between some dilemmas managing the child ViewControllers especially when we need access to them from the TabBarController. There are several different ways of accomplishing it depending on several more factors like weight or intention of the tasks, some of them being:</p><ol><li>Child View Controller positions should be easily changed/switched without much issues but subjective design.</li><li>Parent TabBarControllers should not have to know much about the child ViewControllers other than the cases they need to communicate.</li><li>Parent TabBarControllers should be able to easily access and accurately distinguish child ViewControllers from each other.</li></ol><p>One simple way of tracking the child ViewControllers is through their <strong>String</strong> tabBarItem.title property. If name comparison is all you need, maybe that will be do?</p><p>But be careful still. Strings are easy to implement and modify, but also very loose if you don’t pay strict attention to them. Using <strong>Strings</strong> as a point of comparison can easily result in a lot of false flags without you knowing, so I would stay away from it for now.</p><p>Another way can be done through <strong>data types</strong>. Similar to the title comparisons, you will probably end up with a lot of if else ‘s and because of this, it is only mostly applicable given no two child ViewControllers share the same type.</p><p>Unlike String comparisons, this may save you from accidentally misinterpreting rogue values. But if you go this route, testing the parent UITabBarController will be extra tricky since since relying on strict data types for identifying objects will limit your mocking capabilities.</p><h4>Describing our Tab Items through Protocols and Enums</h4><p>Another way of managing child View Controllers that I’d like to share with you, is through a mix of Swift Enum and Protocol Implementation. By creating a finite set of TabBar identity values for your child ViewControllers to hold, you also improve their testability by giving them a good base for mock or test classes.</p><p>First, We’ll implement our finite set of identities namedTabBarType through a set of Enum values representing our expected TabBar Items.</p><pre>enum TabBarType: String {</pre><pre>    case featured = &quot;Featured&quot;</pre><pre>    case accounts = &quot;Accounts&quot;</pre><pre>    case cart = &quot;Cart&quot;</pre><pre>    case search = &quot;Search&quot;</pre><pre>    case none = &quot;None&quot;</pre><pre>}</pre><p>This way we can lock down our possible values to make sure we can catch any rogues as early as compile time.</p><p>Second, we’ll create a short Protocol named TabBarChild to describe an object that holds a TabBarType value representing them.</p><pre>protocol TabBarChild {</pre><pre>    var tabBarType: TabBarType? { get set }</pre><pre>}</pre><p>Third, we’ll make our designated child ViewController classes conform to the new protocol so their parents know how to communicate to them as TabBar children. This can be accomplished in many different ways depending on your team’s preferred <a href="https://hackernoon.com/tagged/design">design</a>, but in this article I can show you a couple.</p><h4>Solution 1: Extending UIViewController</h4><p>The simpler one is through extending the UIViewController class to conform to the TabBarChild protocol. You basically just assume every UIViewController to be TabBarChild -capable with the drawback of having to design ViewControllers to store/compute the value of TabBarType a little less conventionally.</p><pre>extension UIViewController: TabBarChild {</pre><pre>    var tabBarType: TabBarType {</pre><pre>        get { return TabBarType(rawValue: tabBarItem.title ?? &quot;&quot; ) ?? .none }</pre><pre>        set { tabBarItem.title = newValue.rawValue }</pre><pre>    }</pre><pre>}</pre><p>In this example, I chose to store its value to the ViewController’s tabBarItem.title. With this, you can easily modify how the ViewController is displayed by simply changing the TabBarType ‘s value. It is a convenient approach as it also lets you assign/remove TabBarType properties. Here’s a sample of what it would look like in implementation:</p><pre>//somewhere in you code<br>let viewController = SearchViewController()<br>viewController.tabBarType = .search<br>tabBarController.viewControllers.append(viewController)</pre><pre>func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -&gt; Bool {</pre><pre>    if viewController.tabBarType == .search {<br>        //do something with the search tab here?</pre><pre>    }</pre><pre>    return true</pre><pre>}</pre><h4>Solution 2: Custom UIViewController Extensions</h4><p>Not a fan of the solution above? Another way is going further and removing TabBarChild ‘s set access, <a href="https://hackernoon.com/tagged/leaving">leaving</a> the conforming object with an immutable TabBarType property so their implementation with sort of look like this:</p><pre>protocol TabBarChild {</pre><pre>    var tabBarType: TabBarType { get }</pre><pre>}</pre><pre>extension AccountsViewController: TabBarChild {</pre><pre>    var tabBarType: TabBarType {</pre><pre>        return .accounts</pre><pre>    }</pre><pre>}</pre><p>This lets you assign TabBarType properties to your child ViewControllers more securely. On your TabBar management layer, accessing them may look like this:</p><pre>//sample UITabBarDelegate calls<br>extension HomeFlowController: UITabBarControllerDelegate {</pre><pre>    func tabBarController(_ tabBarController: UITabBarController,     shouldSelect viewController: UIViewController) -&gt; Bool {</pre><pre>        if let tabBarChild = viewController as? TabBarChild,</pre><pre>            tabBarChild.tabBarType == .accounts {</pre><pre>            //do something with accounts tab here?</pre><pre>        }</pre><pre>        return true</pre><pre>    }</pre><pre>}</pre><p>Since it is agnostic about your child ViewController type, you can easily keep the changes in your ViewController implementation from directly affecting your Tab Management logic.</p><h4>What’s Next?</h4><p>The solutions I presented here can definitely be further expanded so try and work around other possibilities. See which one may work best for you and your team. Would adding more properties/functions to TabBarChild protocol help you better? Or would a more simplified version do the job just right?</p><p>And if you got your own solutions, please feel free to share them here and I’m very interested to hear about them!</p><h3>You made it all the way here!</h3><blockquote>I hope that you got what you’re looking for when you opened this article. If so, I would very much appreciate it if you would recommend this to your friends ^^</blockquote><p>if you have any more questions/feedbacks, please feel free to drop a <a href="https://twitter.com/raymundcat">message</a>!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0e37be8ae21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/tabbar-items-with-swift-enums-c0e37be8ae21">TabBar Items with Swift Enums</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[sWrapping up APIs with PromiseKit]]></title>
            <link>https://medium.com/hackernoon/wrapping-up-apis-with-promisekit-d1302f446ad6?source=rss-c2605a55a531------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1302f446ad6</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[promisekit]]></category>
            <dc:creator><![CDATA[john raymund catahay]]></dc:creator>
            <pubDate>Mon, 13 Nov 2017 18:54:49 GMT</pubDate>
            <atom:updated>2019-05-17T10:50:36.533Z</atom:updated>
            <content:encoded><![CDATA[<h4>Actually just some code snippets I’d like to share with you</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwJBXtKMQFcv73_hgIvsCg.jpeg" /></figure><p>New to Promises and how to use them in iOS development? then please feel free read this short introduction I wrote previously on this topic: <a href="https://hackernoon.com/promise-pattern-on-swift-with-promisekit-620efad7a5bd">https://hackernoon.com/promise-pattern-on-swift-with-promisekit-620efad7a5bd</a></p><p>Promises are fun I swear!</p><p>On my previous article, I showed some examples on you how you can convert your async call pyramids into a more organised chain of promises like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/660bb04826b5596c77c370292fafcca3/href">https://medium.com/media/660bb04826b5596c77c370292fafcca3/href</a></iframe><p>More so, wrap them up without changing your original API implementations and end up with something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/245c1341ace3de8cd01379a81b6739cc/href">https://medium.com/media/245c1341ace3de8cd01379a81b6739cc/href</a></iframe><p>The above <a href="https://hackernoon.com/tagged/implementation">implementation</a> was possible by creating a single reusable wrapper <a href="https://hackernoon.com/tagged/function">function</a> that provides you the closure you need when handling async callbacks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54f8b84b571d7c5920f6fac89cfe2157/href">https://medium.com/media/54f8b84b571d7c5920f6fac89cfe2157/href</a></iframe><p>The wrapper function <em>holds reference to the completion block that you can give to your async calls and then return you a </em><strong><em>Promise</em></strong><em> object that you can listen to instead</em>. Here’s a more detailed implementation of our custom wrapper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4db858ffa0956d4b25adf533d79e54b/href">https://medium.com/media/b4db858ffa0956d4b25adf533d79e54b/href</a></iframe><p>With this in mind, let’s see how else can we tidy up in our code ~</p><h4><strong>Involving Third parties in your flow</strong></h4><p>Social media logins are pretty common in application designs and have even been quite a staple user requirement to most of our apps. Because of this, Facebook SDK’s <em>LoginManager</em> and <em>GraphAPI </em>have been two<em> </em>very familiar libraries that are often part of our architecture.</p><p>Third party SDKs are neat for several reasons:</p><ol><li>Saves you and your team a LOT of time when you don’t have to reinvent the wheel.</li><li>Reliable Third parties mean they maintain and test their code very well.</li><li>Libraries that are public and used by thousands~ of people mean issues are found and resolved more easily.</li></ol><p>But of course they may also come with some drawbacks, especially:</p><ol><li>SDKs are often HUGE. So many things you often don’t need to see.</li><li>They are also often designed way differently than your team’s. Be prepared to abstract.</li></ol><p>And Facebook SDK is not any different. In this very particular case, we will be looking at how we may integrate Facebook API calls into our Promises chain.</p><h4>API Example: FB LoginManager</h4><p>What makes Facebook an easy Social Integration to apps is LoginManager.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0eab011fea73f40b0b11806d9197471/href">https://medium.com/media/c0eab011fea73f40b0b11806d9197471/href</a></iframe><p>But it having its own a async callback may create some problems with your data flow especially when you have already designed them through Promises. Let’s take a look at its ‘completion’ callback and see how can we design a wrapper for it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe210e658c7279216246745ae2365076/href">https://medium.com/media/fe210e658c7279216246745ae2365076/href</a></iframe><p>What we want here is to be able to replace the completion closure ‘<strong>((LoginResult) -&gt; Void)? = nil’ </strong>with one that is from our wrapper function.</p><p>So first, let’s declare our new wrapper that takes a completion block whose parameter type is the same as the login completion:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/786d8c77d85a802ce48f3603cf57cd84/href">https://medium.com/media/786d8c77d85a802ce48f3603cf57cd84/href</a></iframe><p>Next, let’s prepare the Promise object by using the completion block parameter to trigger the Promise’s fulfil() and reject(). And while we’re at it, let’s go ahead and return the resulting Promise, using the LoginResult’s successful object type of course.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/474817c996d5b208be589b099afc8086/href">https://medium.com/media/474817c996d5b208be589b099afc8086/href</a></iframe><p>And when that’s all well wrapped up, you should be able to chain your Facebook login calls just like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0864d26c251126b79e792720740e21d0/href">https://medium.com/media/0864d26c251126b79e792720740e21d0/href</a></iframe><h4>What’s next?</h4><p>Having built so many Restful Apps, my team and I are so used to organising and chaining asynchronous calls neatly with PromiseKit whenever we get the chance.</p><p>After what we’ve learned here, I’m encouraging you to look through your code base as well to hunt down those pesky async call pyramids and see a good solution for cleaning them up.</p><p>I wish you best of luck!</p><h3>You made it all the way here!</h3><blockquote>I hope that you got what you’re looking for when you opened this article. If so, I would very much appreciate it if you would recommend this to your friends ^^</blockquote><p>If you have any more questions/feedbacks, please feel free to drop a <a href="https://twitter.com/raymundcat">message</a>!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1302f446ad6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/wrapping-up-apis-with-promisekit-d1302f446ad6">sWrapping up APIs with PromiseKit</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promise Pattern on Swift with PromiseKit]]></title>
            <link>https://medium.com/hackernoon/promise-pattern-on-swift-with-promisekit-620efad7a5bd?source=rss-c2605a55a531------2</link>
            <guid isPermaLink="false">https://medium.com/p/620efad7a5bd</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[john raymund catahay]]></dc:creator>
            <pubDate>Sun, 09 Jul 2017 17:52:58 GMT</pubDate>
            <atom:updated>2019-05-17T10:50:38.399Z</atom:updated>
            <content:encoded><![CDATA[<h4>And why you should migrate your async calls to them</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpX0H4v8JM5efPJ-FmFleA.jpeg" /></figure><p>Asynchronous API/Server calls are almost a staple on mobile apps with several advantages from offloading hardware work, to designing reliable network behaviors.</p><p>If you have been developing iOS Apps for some time now, you probably already know the usual conventions on this: <strong>Closures</strong></p><blockquote>Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables. Swift handles all of the memory <a href="https://hackernoon.com/tagged/management">management</a> of capturing for you.</blockquote><blockquote>~https://developer.apple.com</blockquote><p>Understandably, it is the preferred <a href="https://hackernoon.com/tagged/design">design</a> pattern for accomplishing light asynchronous communication. You can quickly let API calls access your local variables where they can call/manipulate them whenever they please.</p><p>Like any OOP pattern they too can be abused. Take for example this beast:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/456cb2a2a367fface7bcb7422c0ff7dc/href">https://medium.com/media/456cb2a2a367fface7bcb7422c0ff7dc/href</a></iframe><p>Looking closely, you’ll see how this code is simply trying to consecutively perform 3 async tasks:</p><ol><li>Upload an image for the User</li><li>Register an account for the User</li><li>Login a token for the User</li></ol><p>Each and every async call comes with a completion block which handles the responses that can be switched in 2 different ways: success or failure.</p><p>Now if writing this wasn’t already an enormous pain for you, wait until you must maintain it. To handle errors and successful responses, you would have to inspect and edit your code from 3 different blocks, that is, if you aren’t already lost tracking which block you’re supposed to be editing.</p><p>Surely, there must be a better way to handle this?</p><h3>The Promise Pattern</h3><blockquote>A promise is an object that represents an asynchronous task. Pass that object around, and write clean, ordered code; a logical, simple, modular stream of progression from one asynchronous task to another.</blockquote><blockquote>~http://promisekit.org/docs</blockquote><p>Sometimes called <strong><em>Futures</em></strong>, <strong><em>Delay, </em></strong>or<strong><em> Deferred </em></strong>on other languages, they’re specifically constructed to handle asynchronous tasks that may or may not succeed.</p><p>But unlike closures, promises are designed to be <strong>passed around </strong>without needing to capture whole contexts and their result only within a block.</p><p>The design works by actually <em>wrapping</em> asynchronous functions around an object and only exposing their <em>promised </em>end result via a <strong><em>.then{ } </em></strong>block, which can then be modified to return another promise or other objects.</p><pre>intPromise.then { intResult -&gt; Promise&lt;Bool&gt; in<br>    return boolPromise()<br>}.then { boolResult -&gt; Promise&lt;String&gt;<br>    return stringPromise()<br>}.then { stringResult -&gt; Void<br>    //finally do something with <br>    //your end result here<br>}.catch { error in<br>    //oh noes error<br>}</pre><p>This example shows how 3 asynchronous functions can be cascaded to each other where all their end results can be handled cleanly using <strong>PromiseKit</strong>.</p><p>Not only are your Errors handled in a single block, all proceeding tasks are arranged in a cleaner order avoiding long indentations.</p><p>Catching everything so far? Awesome!</p><p>Now let’s see if we can transform our original “registration” code to something similar.</p><h3>Integrating PromiseKit</h3><pre>use_frameworks!<br>swift_version = &quot;3.0&quot;<br>pod &quot;PromiseKit&quot;, &quot;~&gt; 4.0&quot;</pre><p>Let’s start by installing the library through pods, or for other methods you prefer, checkout their readme <a href="https://github.com/mxcl/PromiseKit">https://github.com/mxcl/PromiseKit</a></p><p>In our previous user registration code, we can see that it uses 3 different server API calls namely:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dcaecc3144331047e514104bb141483/href">https://medium.com/media/2dcaecc3144331047e514104bb141483/href</a></iframe><p>It looks clean on paper, yes? Let’s see how else we can improve this.</p><h4>Converting Async Calls</h4><p>We’re going to start by fully revising our calls from taking <strong>Closures </strong>as parameters:</p><pre>func asyncCall(parameter: String, completion: (String) -&gt; Void)</pre><p>to returning Promises:</p><pre>func asyncCall(parameter: String) -&gt; Promise&lt;String&gt;</pre><p>A Promise Object is going to be created with a block, having a <strong><em>fulfill</em></strong> and <strong><em>reject</em></strong> parameters. These two are simple functions that will take your Generic Typed parameter or an Error as a result.</p><p>You are free to implement your async calls inside this block, then call the parameters to send a result signal.</p><p>Ideally, your refactored functions would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59530bc7f5b8c3aca3bb5103606dad27/href">https://medium.com/media/59530bc7f5b8c3aca3bb5103606dad27/href</a></iframe><p>Also, notice that we are now mocking an error result. This is simply for error handling demonstrations. Now try to do the whole registration flow again with the new Promises:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53df4fb5dc1e34d02468a08e71e0cfca/href">https://medium.com/media/53df4fb5dc1e34d02468a08e71e0cfca/href</a></iframe><p>Now doesn’t that look better? Now you can easily manage where your calls, results and errors go. It’s very readable and maintainable.</p><h4>Wrapping Existing Async Calls</h4><p>If creating new Promises for each API call you have seem little too much for your development flow, there is another option for you. It’s a little more tedious to implement, but it means less new API writing:</p><pre>public func wrap&lt;T&gt;(_ body: (@escaping (T?, Error?) -&gt; Void) throws -&gt; Void) -&gt; Promise&lt;T&gt;</pre><p><strong>Wrap </strong>functions are available from PromiseKit’s library and they come with different parameter options depending on your case. In this case, say you have a function that looks like this:</p><pre>func asyncCall(parameter: String, completion: @escaping (Token?, Error?) -&gt; Void)</pre><p>Wrapping it will simply look like this:</p><pre>wrap({ asyncCall(parameter: String, completion: $0) })</pre><p>Now this will return a new Promise which will copy your original result type and pass it as its own. Since we (well, at least <em>I</em> do) are writing our result objects represented by an Enum:</p><pre>enum Result&lt;T&gt;{</pre><pre>case success(result: T)</pre><pre>case failure(error: Error)</pre><pre>}</pre><p>We have to write a new wrapping function to accommodate our flow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee036119354d5dfb51ec806d8561c2e1/href">https://medium.com/media/ee036119354d5dfb51ec806d8561c2e1/href</a></iframe><p>Looking closely and you’ll see how this simply takes your closure block and converts it into a Promise object.</p><p>Now try to implement the original registration flow again, but now with wrapped closures:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/245c1341ace3de8cd01379a81b6739cc/href">https://medium.com/media/245c1341ace3de8cd01379a81b6739cc/href</a></iframe><p>Looks like you have to write more characters, yes?</p><p>I prefer this for most cases. It saves me from having to rewrite or duplicate my functions, resulting in fewer possible errors and better code maintainability.</p><h4>Alamofire Promises</h4><p>If you use Alamofire for your REST calls, then you should checkout their Alamofire extension library that you can get through</p><pre>pod &#39;PromiseKit/Alamofire&#39;, &#39;~&gt; 4.0&#39;</pre><p>or check the whole readme here: <a href="https://github.com/PromiseKit/Alamofire-">https://github.com/PromiseKit/Alamofire-</a></p><p>It comes with options such as:</p><pre>public func responseJsonDictionary(options: JSONSerialization.ReadingOptions = .allowFragments) -&gt; Promise&lt;[String: Any]&gt;</pre><p>which lets Alamofire’s DataRequests to return a Promise object instead of you having to capture them all through a block. An example would be a login call like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7728cd72eb61a332e4c4aff7468dfd55/href">https://medium.com/media/7728cd72eb61a332e4c4aff7468dfd55/href</a></iframe><p>This is one of the few cases where I use <strong><em>throw </em></strong>to handle errors, and it works very cleanly.</p><h4>What’s next?</h4><p>Promises are fun! Start by slowly integrating them into your projects where you see fit. Read more of the awesome uses of PromiseKit, straight from their website: <a href="http://promisekit.org/docs/">http://promisekit.org/docs/</a></p><p>Look for places where closures are starting to get messy. Try wrapping up some of your functions. Introduce more Promises instead of completion blocks to your code.</p><p>And just like trying out any new design patterns, don’t be afraid to step back and reevaluate if they truly fit your style.</p><p>I wish you best of luck!</p><h4>Quick Follow Up</h4><p>If you would like to see a more in depth guide on how to manage you custom async calls, I have written a short guide on it so feel free to check it out:</p><p><a href="https://hackernoon.com/wrapping-up-apis-with-promisekit-d1302f446ad6">https://hackernoon.com/wrapping-up-apis-with-promisekit-d1302f446ad6</a></p><h3>You made it all the way here!</h3><blockquote>I hope that you got what you’re looking for when you opened this article. If so, I would very much appreciate it if you would recommend this to your friends ^^</blockquote><p>If you have any more questions/feedbacks, please feel free to drop a <a href="https://twitter.com/raymundcat">message</a>!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=620efad7a5bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/promise-pattern-on-swift-with-promisekit-620efad7a5bd">Promise Pattern on Swift with PromiseKit</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observer Pattern on Swift with Signals]]></title>
            <link>https://medium.com/hackernoon/observer-pattern-on-swift-with-signals-4699168e57ec?source=rss-c2605a55a531------2</link>
            <guid isPermaLink="false">https://medium.com/p/4699168e57ec</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[john raymund catahay]]></dc:creator>
            <pubDate>Sun, 12 Feb 2017 16:37:27 GMT</pubDate>
            <atom:updated>2019-05-17T10:50:39.190Z</atom:updated>
            <content:encoded><![CDATA[<h4>An attach-and-forget library for your iOS Projects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebBDG6xilDgwAv2tuS_O3Q.jpeg" /></figure><h3>The Observer Pattern</h3><p>The Observer Patter (sometimes also called Notifications, Broadcast-Listener, or Publish-Subscribe pattern) is a communication style common in OOP languages, much like Delegation (useful on a Parent-Children relationship) and Blocks (useful on Concurrent/Asynchronous tasks). The concept is to enable objects to “listen” or “observe” data from a relatively unrelated source.</p><p>Think: radio broadcast. The source of the analog signals simply broadcasts them on air, regardless of whether anything is listening. The receivers simply listens, regardless of whether a signal is actually being sent. The same relationship is to be considered when choosing this pattern for data communication.</p><h3>Signals Library</h3><p>I came across this awesome <a href="https://github.com/artman/Signals">library</a> while looking for alternative methods to implement an Observer Pattern. I liked this one particularly because of its simple implementation. It basically goes like this:</p><ul><li>Create a <strong>Signal Object</strong>.</li><li><strong>Fire</strong> that Signal Object.</li><li><strong>Subscribe</strong> to that Signal Object from anywhere in your project.</li></ul><h4><strong>Create a Signal Object</strong></h4><p>Initialize a Signal Object and pass the data type of your broadcast ‘message’ as its parameter</p><pre>let onData = Signal&lt;(data:NSData, error:NSError)&gt;()<br>let onProgress = Signal&lt;Float&gt;()</pre><h4><strong><em>Fire</em></strong> that Signal Object</h4><p>Simply call the method <strong><em>fire(_ data: T)</em></strong> on your Signal Objects and it will broadcast your data to all of its subscribers.</p><pre>func receivedData(receivedData:NSData, receivedError:NSError) {<br>    // Whenever appropriate, fire off any of the signals<br>    self.onProgress.fire(1.0)<br>    self.onData.fire((data:receivedData, error:receivedError))<br>}</pre><h4><strong><em>Subscribe </em></strong>to that Signal Object</h4><p>Subscribing to a Signal takes a closure with the data as parameters. It will be called whenever a data was fired.</p><pre>onProgress.subscribe(on: self) { (progress) in<br>    print(&quot;Loading progress: \(progress*100)%&quot;)<br>}</pre><pre>onData.subscribe(on: self) { (data, error) in<br>    // Do something with the data<br>}</pre><p>The “attach-and-forget” usage is also very cool as it removes the hassle of observing your object’s life cycles — avoiding memory leaks due to unbound listener bindings. If you want to read more on the Signals library, follow this <a href="https://github.com/artman/Signals">github link</a> for its official documentation.</p><h3>Exercise: A Mock Downloader App</h3><p>In this short tutorial, let me demonstrate the use of this library and <a href="https://hackernoon.com/tagged/programming">programming</a> pattern with a dummy “file downloader” app. This app is supposed to function like a download manager. CoreData and Asynchronous <a href="https://hackernoon.com/tagged/network">Network</a> Tasks are huge topics on their own so we will skip those and implement a dummy download task. We’ll have them broadcast their ongoing tasks for any listeners you may need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*2226NQTIsr261Onx5B6gPQ.png" /><figcaption>Our target is literally this simple.</figcaption></figure><p>To save you the hassle of doing all the boiler plate codes of creating a Tableview, Cells and Data Sources, I’ve created a starting project which you can download <a href="https://github.com/raymundcat/SignalsTutorialInitial">here</a>.</p><h4>1. Project Overview</h4><p>Okay, here’s a quick overview of our template project. We’ll be implementing a light MVP-MVVM design so expect the usual suspects (Views, Models, Presenters, Interactors, etc). Here we have a simple <strong>DownloadViewController</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d362d8a032c613c127d9c0fa78534391/href">https://medium.com/media/d362d8a032c613c127d9c0fa78534391/href</a></iframe><p>Simple and straightforward. It contains our tableView (plugged in via interface builder) and its datasource and delegate methods.</p><p>It holds a set of two models, an array of <strong>DownloadableItems</strong> and a dictionary of <strong>DownloadTasks</strong>. These two automatically gets plugged in to our tableViewCells to present our download object’s name and download status if it’s currently being downloaded.</p><p>The ViewController also follows a <strong>PresenterDelegate</strong> protocol, which gives us access to receiving data from our Presenter.</p><p>Our <strong>Presenter</strong> here holds all the logic outside the view, and practically becomes the logical identity of our screen/scene/page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5db047a96a4275e1b342242dadcce843/href">https://medium.com/media/5db047a96a4275e1b342242dadcce843/href</a></iframe><p>Presenter has three objects to fulfill its responsibility, objects that <strong>CanFetchItems</strong>, <strong>CanDownloadItems</strong>, and <strong>CanBroadcastTasks</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ef7813fb5749cbe2007a5d9b735785e/href">https://medium.com/media/3ef7813fb5749cbe2007a5d9b735785e/href</a></iframe><p>For our dummy app, all of them will be fulfilled by dummy classes, of course.</p><p><strong>CanFetchItems</strong> will be held by an ItemStore that provides an array of statically-generated objects.</p><p><strong>CanDownloadItems</strong> will be fulfilled by a class with a dummy requestDownload(item:) method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deb23d25414b1c92e528aa1a0fde8c3c/href">https://medium.com/media/deb23d25414b1c92e528aa1a0fde8c3c/href</a></iframe><p>For now this will be held by our <strong>DownloadManager</strong>, which will mock a download request by creating a <strong>DownloadTask</strong> — an object that can hold an item’s download progress.</p><p><strong>CanBroadcastTasks </strong>will be fulfilled by a class that holds a Signal object, specifically one that broadcasts a dictionary of <strong>DownloadTasks</strong>.</p><p>In our case, this will be held (again), by our DownloadManager since this class will be the one initiating the downloads and managing their queue of tasks.</p><p>Still following? :D Now let’s start coding.</p><h4>2. Initiate the download task</h4><p>First we’ll be editing our DownloadManager’s requestDownload(item:) method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38032f45e831330b46ffda203f87ad11/href">https://medium.com/media/38032f45e831330b46ffda203f87ad11/href</a></iframe><p>We’ll be creating a DownloadTask from the item and give it an initial progress value.</p><p>To increment our download progress’s value asynchronously, we’ll be using a Timer schedule function which will be called at every 1/4 of a second. This updates our current task queue with each increment and removes it when the task is finished.</p><h4>3. Broadcast the tasks</h4><p>Still in our DownloadManager, we’ll override the init() method to initiate a Timer schedule again, which will then continuously broadcast our queue of tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f420d314426ab99cc286d8f925bcc13/href">https://medium.com/media/7f420d314426ab99cc286d8f925bcc13/href</a></iframe><p>We’ll automate our broadcast here so we don’t spam our listeners with too many calls. Our broadcasts will be consistent ticks instead of automatic firing whenever an update has been made.</p><h4>4. Listen to broadcasts</h4><p>Now that we have setup our broadcasters, let’s go back to our Presenter and start listening.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0881115350ab93e30574958e9524fc8a/href">https://medium.com/media/0881115350ab93e30574958e9524fc8a/href</a></iframe><p>In our Presenter’s viewDidLoad(), add the subscribe method so we can start listening immediately after our view gets loaded. Pass the callback’s returned<em> tasks</em> to your Presenter’ <em>tasks</em>. It will then be passed to your View’s <em>tasks</em>, and subsequently presented to your user. Everything happens in somewhat a reactive manner.</p><p>Run the code now, and you should be able to get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*byg2BsHk7-cfeJjJx3mRBQ.gif" /></figure><p>Didn’t run? Grab a copy of the final project <a href="https://github.com/raymundcat/SignalsTutorialComplete">here</a> and see if you got everything right.</p><h4>What’s Next?</h4><p>Well. Now that you have a working pattern implementation, try to have more Observers by adding another ViewController and Presenter. This time, with a TableView, try to show all the working DownloadTasks <strong>only</strong></p><h4>Have fun!</h4><h3>Before you get too comfy..</h3><p>A few remarks about the topic: The Observer Pattern is a good option to avoid a lot of relationship complications (like too much delegations and callback-ceptions). It can still be abused. Here are some <strong>Don’ts</strong> to remember when broadcasting your objects:</p><h4>1. Overbroadcasting updates with little significance</h4><p>I guess we can say that spamming is part of the nature of this pattern. Still, be mindful about the scalability of your implementation and the fact that you are running on a limited hardware.</p><p>In our example, I placed the broadcast call outside the actual items update methods and into a dedicated timer. When you have hundreds of ongoing downloads, this would mean you would be broadcasting hundreds or thousands of download progresses per second.</p><p>This could potentially clog your Main Thread with unnecessary update calls to your views and drastically impair the usability of your app. When implementing this design, <strong>try to keep the pace as minimal as necessary</strong>.</p><h4>2. Ruining your architecture for convenience</h4><p>It’s tempting. You could be directly listening for broadcasts from your View Layer, past your Presenters, because you can. With this, you can just update your view without the Presenter knowing.</p><p>But if we do this, we would violate the concept of MVP. Our View starts to manage its own business models and our Presenter starts to lose control over the View. If the Presenter receives an update, it can’t be sure if its data is consistent with the ones presented on the View.</p><p>When integrating this pattern, be mindful of your architecture standards and don’t let the convenience override your own rules.</p><h3>You made it all the way here!</h3><blockquote>I hope that you got what you’re looking for when you opened this article. If so, I would very much appreciate it if you would recommend this to your friends ^^</blockquote><p>if you have any more questions/feedbacks, please feel free to drop a <a href="https://twitter.com/raymundcat">message</a>!</p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4699168e57ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/observer-pattern-on-swift-with-signals-4699168e57ec">Observer Pattern on Swift with Signals</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>