<?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 Ryan Quan on Medium]]></title>
        <description><![CDATA[Stories by Ryan Quan on Medium]]></description>
        <link>https://medium.com/@ryanquan?source=rss-af9853cf94fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rB70btkhyg3CzPdK.jpg</url>
            <title>Stories by Ryan Quan on Medium</title>
            <link>https://medium.com/@ryanquan?source=rss-af9853cf94fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:20:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryanquan/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[Reloading UITableView while Animating Scroll in iOS 11]]></title>
            <link>https://medium.com/brigade-engineering/reloading-uitableview-while-animating-scroll-in-ios-11-f89910c958b6?source=rss-af9853cf94fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f89910c958b6</guid>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[scroll-animation]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-11]]></category>
            <dc:creator><![CDATA[Ryan Quan]]></dc:creator>
            <pubDate>Thu, 08 Mar 2018 23:50:55 GMT</pubDate>
            <atom:updated>2018-03-08T23:50:55.053Z</atom:updated>
            <content:encoded><![CDATA[<p>Calling reloadData on UITableView may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your UITableView is showing. In iOS 10 reloadData could be called at any time and it would not affect the scrolling UI of UITableView. However, in iOS 11 calling reloadData while your UITableView is animating scrolling causes the UITableView to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the UITableView methods (such as scrollToRow(at:at:animated:)) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a reloadData call since they can happen at any moment, possibly when scroll animation is occurring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*_CWQFyVQMy90G5FDZFjjUw.gif" /><figcaption>Example of scroll animation getting interrupted by a `reloadData` call</figcaption></figure><h4>Solution</h4><p>If you don’t want to switch to updating cells individually, one solution is to defer your reloadData call until all scroll animations are complete. We use a utility class to encapsulate interactions with aUITableView.</p><pre>class TableViewUtility {</pre><pre>    let tableView: UITableView<br>    var data: Data?<br>    <br>    init(tableView: UITableView) {<br>        self.tableView = tableView<br>    }</pre><pre>    func showData(_ data: Data) {<br>        self.data = data<br>        tableView.reloadData()<br>    }</pre><pre>    // Other UITableViewDataSource and UITableViewDelegate methods<br>}</pre><p>Now we add:</p><ul><li>A method to animate scrolling (here we use scrolling an index path to the bottom of the UITableView as an example)</li></ul><pre>func scrollIndexPathToBottom(indexPath: IndexPath) {<br>   isAnimatingScroll = true<br>   tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)<br>}</pre><ul><li>A variable to keep track of whether or not scroll is being animated</li></ul><pre>var isAnimatingScroll = false</pre><ul><li>A variable to store any Data we need to load once scroll animations have completed</li></ul><pre>var pendingData: Data?</pre><ul><li>Update showData to store Data if scroll animation is occurring when we try to reload the table</li></ul><pre>func showData(_ data: Data) {<br>    guard !isAnimatingScroll else {<br>        pendingData = data<br>        return<br>    }</pre><pre>    self.data = data<br>    tableView.reloadData()<br>}</pre><p>Altogether it looks like:</p><pre>class TableViewUtility {<br>    ...</pre><pre>    var isAnimatingScroll = false<br>    var pendingData: Data?</pre><pre>    func scrollIndexPathToBottom(indexPath: IndexPath) {<br>        isAnimatingScroll = true<br>        tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)<br>    }</pre><pre>    func showData(_ data: Data) {<br>        guard !isAnimatingScroll else {<br>            pendingData = data<br>            return<br>        }</pre><pre>        self.data = data<br>        tableView.reloadData()<br>    }<br>}</pre><p>Now we need to figure out when scroll animations are finished so we can show any pendingData. Unfortunately the scroll methods that give us scroll animations for UITableView don’t take completion blocks. We found that putting these calls into a CATransaction and setting a completion block didn’t work either, so we used the UIScrollViewDelegate method scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView)</p><pre>func scrollViewDidEndScrollingAnimation(_ scroll: UIScrollView) {<br>    isAnimatingScroll = false<br>    if let pendingData = pendingData {<br>        showData(pendingData)<br>        pendingData = nil<br>    }<br>}</pre><p>There is one gotcha with this. If tableView.scrollToRow(at:at:animated:) is called when the given IndexPath is already at the specified position, scrollViewDidEndScrollingAnimation does not get triggered since no scrolling animation occurred. To make sure our isAnimatingScroll flag doesn’t get stuck with a value of true , we have to make sure the IndexPath we’re scrolling to is not already in position:</p><pre>func scrollIndexPathToBottom(indexPath: IndexPath) {<br>    let scrollPadding: CGFloat = 1.0<br>    let indexRect = tableView.rectForRow(at: indexPath)<br>    let targetScrollYOffset = indexRect.origin.y - tableView.frame.height + indexRect.size.height + tableView.contentInset.bottom</pre><pre>    guard fabs(tableView.contentOffset.y - targetScrollYOffset) &gt; scrollPadding else {<br>        return<br>    }    </pre><pre>    isAnimatingScroll = true<br>    tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)<br>    }</pre><p>We use a scrollPadding of 1.0 here to account for small inconsistencies in view placements.</p><p>The final thing to watch out for is if you are updating cells individually as well, make sure your pendingData is updated appropriately otherwise you may get stale data being loaded after scroll animations. This means <strong>all</strong> potential properties of your data should be up to date. For example, if a scroll animation gets triggered and two separate properties of your data get updates, the pendingData should have both of these changes. This may seem obvious, but it can be subtle depending on your app architecture.</p><h4>The Result</h4><p>With this, we get smooth scroll animations even when we try to reload the data mid-animation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*vk9tIjCNaPxtXfjTNUbTcg.gif" /></figure><p>If you’ve encountered this problem as well, feel free to leave a comment on how you solved it or if this method was helpful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f89910c958b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brigade-engineering/reloading-uitableview-while-animating-scroll-in-ios-11-f89910c958b6">Reloading UITableView while Animating Scroll in iOS 11</a> was originally published in <a href="https://medium.com/brigade-engineering">Brigade Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RQVisual — A Simple Way to Layout Views]]></title>
            <link>https://medium.com/@ryanquan/rqvisual-a-simple-way-to-layout-views-685eabc2c39a?source=rss-af9853cf94fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/685eabc2c39a</guid>
            <dc:creator><![CDATA[Ryan Quan]]></dc:creator>
            <pubDate>Mon, 13 Jul 2015 02:30:36 GMT</pubDate>
            <atom:updated>2015-07-13T02:30:36.034Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reduce layout code in your iOS applications</h4><p>When laying out views for a UI it can either be done in IB or in code. Both of these methods have their pros and cons. Merge conflicts in .xib files can be annoying, but IB does allow for quick composition of views with constraints. Laying out views in code can blow up your file’s line count and make it hard to visualize the end composition, but it is easier to refactor a view out into a separate component if it’s been constructed in code and code constraints can be applied at run time. RQVisual aims to make laying out views in code as simple as a single line of code while also making it easy to visualize the end result.</p><h3>But wait, we already have Auto Layout’s Visual Format Language</h3><p>Auto Layout’s Visual Format Language definitely cuts down the code you need to construct a view, but it’s still hard to visualize the end result at a glance. Also, why not make it so both horizontal and vertical constraints can be applied in the same method call? I’ll be using Auto Layout’s Visual Format Language as a comparison when I go through my example of RQVisual.</p><h3>Laying out views</h3><p>The view we’ll be constructing is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*B0xNADb-LySSf4N0ZvQW_g.png" /></figure><p>With frames shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*_oD6hZC3t-amRzYWDdAyqw.png" /></figure><p>For this we have a UIImageView, a UILabel, and a UITextView:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fba43392628c98ec5f7ff2e22ddf47b/href">https://medium.com/media/6fba43392628c98ec5f7ff2e22ddf47b/href</a></iframe><p>Using Auto Layout’s Visual Format Language we’d do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/057a3ef6247f65bfad62195bf5640676/href">https://medium.com/media/057a3ef6247f65bfad62195bf5640676/href</a></iframe><p>Using RQVisual we’d do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed3227ad454faec0d626c384619c7875/href">https://medium.com/media/ed3227ad454faec0d626c384619c7875/href</a></iframe><p>Before I explain this syntax, I did promise a single line of code (split into 4 for readability):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a76f7af8f021f2366268f41a798ebbae/href">https://medium.com/media/a76f7af8f021f2366268f41a798ebbae/href</a></iframe><p>The idea behind RQVisual is that the majority of views can be constructed by thinking of a view layout as multiple rows with a variable number of columns per row. Using this idea, RQVisual’s Visual Formats represent entire rows and an array of Visual Formats represents a composition of rows. In our example, the `imageView` and `title` make up one row of two columns and the `textView` makes up a second row with a single column. This syntax solves a few problems:</p><ul><li>It’s easier to visualize what the end result will look like by being able to stack visual formats on adjacent lines to mimic a sort of ascii representation of the view.</li><li>Rearranging views becomes simpler because the name representations in the Visual Formats just have to be swapped around.</li><li>The number of lines of code are reduced dramatically</li></ul><p>Of course we do lose some of the flexibility that we had with Auto Layout’s Visual Format Language, but for the majority of cases I’ve found that extra flexibility is unnecessary.</p><p>There are some other cool features that I haven’t touched on such as being able to pin views to the right or left edges or centering views. Check out <a href="https://github.com/rqueue/RQVisual">RQVisual on Github</a> for more in depth examples and check out the <a href="https://github.com/rqueue/RQVisual/wiki/Documentation">wiki</a> for some more syntax information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685eabc2c39a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brigade’s Experience Using an MVC Alternative]]></title>
            <link>https://medium.com/brigade-engineering/brigades-experience-using-an-mvc-alternative-36ef1601a41f?source=rss-af9853cf94fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/36ef1601a41f</guid>
            <category><![CDATA[viper]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mvc]]></category>
            <dc:creator><![CDATA[Ryan Quan]]></dc:creator>
            <pubDate>Mon, 15 Sep 2014 17:09:25 GMT</pubDate>
            <atom:updated>2016-10-31T19:24:12.838Z</atom:updated>
            <content:encoded><![CDATA[<p>VIPER architecture for iOS applications</p><p>Any iOS developer will tell you that iOS apps are built upon the <a href="https://developer.apple.com/library/ios/documentation/general/conceptual/devpedia-cocoacore/MVC.html">Model-View-Controller</a> (MVC) design pattern. They might also tell you that some like to call it the “Massive View Controller” design pattern. Reason being, you’ll often find you have code that clearly doesn’t fit in the view or model, so it gets chucked into the controller, resulting in a bloated controller that is difficult to maintain because you have one giant class doing everything.</p><p>In developing <a href="https://www.brigade.com/">Brigade</a>’s iOS app, we wanted to architect it in such a way that cleanly addressed a few key points:</p><ul><li>Easy to iterate on</li><li>Collaboration-friendly</li><li>Separated concerns</li><li>Easy to test</li></ul><p>We stumbled upon an architecture called VIPER, which seemed to fit the bill. VIPER was developed by the guys over at Mutual Mobile and they have a nice <a href="http://mutualmobile.github.io/blog/2013/12/04/viper-introduction/">introductory blog post</a> as well as a more <a href="http://www.objc.io/issue-13/viper.html">involved blog post</a>. We decided to stray from the Apple standard and give VIPER a shot.</p><h3>What is VIPER and how are we using it?</h3><p>As stated by its creators, VIPER provides a guide to building an application architecture and can be adjusted to fit individual applications. This will be a discussion of what VIPER is and how we’ve adjusted it to fit our needs.</p><p>To best understand VIPER, forget everything you know about MVC. VIPER is a new kind of beast (or reptile) and if your mindset is still in MVC land, you’ll have a difficult time accepting VIPER. Imagine that you are starting from square one and have no idea how iOS apps are structured. There is no spoon. There is no MVC.</p><p>VIPER aims to separate out application concerns into one of several roles:</p><ul><li>View/User Interface</li><li>Interactor</li><li>Presenter/Event Handler</li><li>Entity</li><li>Router/Wireframe</li></ul><p><em>Note: Some of these have alternative names that you’ll see if you look at the other VIPER blog posts referenced above. I’ve added both names here as a heads up.</em></p><p>In practice, we’ve found that we use a few additional roles, adding on a data-manager and service layer.</p><p>Below is a diagram of a typical VIPER “stack” (more on this later) in our app and depicts how we think of VIPER. Each box represents a separate class and each line represents a reference between instances of the two respective classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*XovYPHm53nQ5H8tSeBx_IQ.png" /></figure><p>Think of each of these classes as a worker in an assembly line. Each class only knows how to carry out a limited set of actions and relies on other classes to aid in completing the task at hand.</p><p>Let’s first go over the responsibilities of each class, then we’ll give an example of going from user interaction to displaying data to the user.</p><h3>View/User Interface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*mmMgaqaPf2tisQJG8tlQng.png" /></figure><p>View responsibilities:</p><ul><li>Display information to the user</li><li>Detect user interaction</li></ul><p>The view is told by the presenter what to display and it tells the presenter when an event needs to happen.</p><h4>Displaying information to the user</h4><p>If the view should display an error to the user, the presenter might call a method on the view like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fab7ec5fab6b329e7f319bc11ab9517/href">https://medium.com/media/0fab7ec5fab6b329e7f319bc11ab9517/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wbZqa4CQmXpBjEvzv3L0kw.png" /></figure><p>It is then up to the view to display the error as it pleases, which could be in an alert view, a label, or any other way. The key thing here is that the presenter isn’t concerned with the details of how the error gets displayed. It just cares that it <em>gets </em>displayed.</p><h4>Detecting user interaction</h4><p>If an event occurs such as the user tapping on a “Log in” button, the view might call a method on the presenter like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd6b70b95a5bf707c5e6efd7d96748d6/href">https://medium.com/media/cd6b70b95a5bf707c5e6efd7d96748d6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEr3x6TgpbaK9BPwkgyJzg.png" /></figure><p>As we had before, the object making the method call just hands off the task to the next worker in line once it’s completed its job. As far as the view is concerned, it completed its job to detect the user interaction and it is now up to the presenter to deal with the event.</p><h3>Presenter/Event handler</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*m0SBR_-COv6EskjU4wsgjg.png" /></figure><p>Presenter responsibilities:</p><ul><li>Tell the view what to display</li><li>Handle events</li></ul><p>The presenter tells the view what to display and it handles events accordingly.</p><h4>Telling the view what to display</h4><p>As we just saw, one of the presenter’s duties is to tell the view what to display. To accomplish this task, it also acts as a decorator, or a “presenter”, to format the data for the view so that it can be displayed in a meaningful way.</p><p>Looking back at our previous error example, the presenter likely received the error in the form of an error object. Instead of handing off the error directly to the view, it determined the appropriate message to describe the error and handed that off to the view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r046Z_kliF5RjrLPidtETA.png" /></figure><h4>Handling events</h4><p>The presenter usually receives event type method calls from two sources: the view and the interactor.</p><p><strong>View events</strong></p><p>The presenter is notified of events by the view and part of its job is to handle those events accordingly. This usually means asking the interactor to retrieve some bit of information or carry out some task.</p><p>In our log in example, the presenter would have been notified by the view that a log in attempt event had occurred with a specific user name and password. The presenter would then ask the interactor to carry out the attempt by calling the appropriate method on it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cde1ed556bb4ebde28c869fa3078f8ad/href">https://medium.com/media/cde1ed556bb4ebde28c869fa3078f8ad/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gl3ZFt2yUGJ_GCbEy_8pBA.png" /></figure><p>You can probably guess what the presenter does now; Nothing. It has carried out its duty of handling the event and it is now up to the interactor to carry on the task.</p><p><strong>Interactor events</strong></p><p>The presenter can also receive events from the interactor. This would happen when the interactor finishes carrying out some task and the user should know about the result.</p><p>For example, if a log in attempt failed, the interactor might tell the presenter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f36665e30630d878fc214865ca9fd786/href">https://medium.com/media/f36665e30630d878fc214865ca9fd786/href</a></iframe><p>The presenter would then take this error, convert it into a string that is meaningful for the user, then tell the view to display an error using that string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BS9djdcmnNCQAxXkMwGuGw.png" /></figure><h3>Interactor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*wlArOkhJfXqhlfDFuoJveg.png" /></figure><p>Interactor responsibilities:</p><ul><li>Perform business logic</li></ul><p>The interactor is what performs the business logic of the app that revolves around data.</p><h4>Performing business logic</h4><p>The interactor is the one that knows how to carry out the events that the view notifies the presenter of.</p><p>For example, suppose that in your app some event occurs that requires two synchronous network requests to your backend API. That is, request B cannot be executed until request A finishes because request B requires information that is in the response of request A. This would start out with a call to the interactor from the presenter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ede34d566fc51c685b730c06ee4b8a62/href">https://medium.com/media/ede34d566fc51c685b730c06ee4b8a62/href</a></iframe><p>One thing we must bring up here is that the interactor itself does not deal with network requests directly. In fact, it doesn’t even know that network requests are occurring. All it knows is that it can get data in the form of <em>entities</em> from the data manager (we’ll elaborate on this concept soon). With that in mind, the interactor’s corresponding method to the call above would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bb41bfe5ab5d68058cb37bc76e20899/href">https://medium.com/media/7bb41bfe5ab5d68058cb37bc76e20899/href</a></iframe><p>Here we see that the interactor calls the necessary methods on the data manager and then calls back to the presenter with the result. The key thing here is that the interactor <em>knows</em> that `performMyTask` requires both `fetchFooWithCallback:` and `fetchBarWithFoo:callback:` to be called AND that `fetchBarWithFoo:callback:` must be called within the callback block of `fetchFooWithCallback`. In this way, the interactor handles the “business logic” of the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*NrZgQI7NYhPoQZuy6icSQg.png" /></figure><h3>Data Manager</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*enr6llNjSGPY6taPP3IWSw.png" /></figure><p>Data manager responsibilities:</p><ul><li>Retrieve data</li><li>Store data (optional)</li></ul><p>The data manager is the one that knows where to retrieve data from and if it should be persisted or not.</p><h4>Retrieving data</h4><p>As we saw in the interactor example, we should be able to query the data manager for data and just get the correct entities back. We don’t care where the data comes from because the data manager handles that.</p><p>The data manager knows exactly where to retrieve specific data or carry out certain requests. For example, the interactor might request a user object from the data manager:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e076d5a84d502095077e7bf966c17edf/href">https://medium.com/media/e076d5a84d502095077e7bf966c17edf/href</a></iframe><p>If this is an app that is backed by a backend server, the data manager would know that it has to eventually make a network request to retrieve user data. If this is an app that is not backed by a backend server, the data manager might retrieve the user data from a local persistent store instead. For network requests, we like to have the data manager query Service objects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fc03bd71a10d9922ed1759edd5fdc38/href">https://medium.com/media/9fc03bd71a10d9922ed1759edd5fdc38/href</a></iframe><p>We’ll get into Service objects soon, but the key here is that the data manager knows what service to use to retrieve specific information. Once that information is received, it relays the information back to the interactor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*F1qTRN49rD_n0QhC2826ow.png" /></figure><h4>Storing data</h4><p>Persisting data is also concern of the data manager. It knows when it should store data such as data fetched from the server that it might store for caching purposes. The main thing here is that no other class knows that any data is persisted because the data manager abstracts that away. A simple example of this is a modification of the code above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf1ecf15eecc1c41aedbe8bfe753b13e/href">https://medium.com/media/cf1ecf15eecc1c41aedbe8bfe753b13e/href</a></iframe><p>Let’s break this down:</p><ul><li>The data manager first checks if it has a cached version of the user corresponding to the given `userID`.</li><li>If the user is found, the interactor is notified and the method returns.</li><li>If the user is not found, the data manager must retrieve the user from the backend server and it uses a Service to do so.</li><li>Once the user is retrieved from the server, the user is first persistent, then the interactor is notified.</li></ul><p>Persisting data is a huge topic all on its own and can be implemented many ways. This example just serves as a simple instructional schema, but the idea of abstracting all of this behind a data manager is one of the points of VIPER.</p><h3>Service</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*psxyw4Su-7uChjj4vqIINA.png" /></figure><p>Service responsibilities:</p><ul><li>Execute network requests to the server for specific entities</li></ul><p>Service objects are not necessary in VIPER, but one that we have found very useful.</p><h4>Executing network requests to the server for specific entities</h4><p>We’ve found Services to be a nice way to keep code concerned with network requests <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>. The idea is that a single Service only deals with one entity type and knows what network requests need to be made to perform various modifications to that entity type.</p><p>For example, you may have a Service for a user entity. The header file for this class might look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f04dc8d4d383ce14396e42942de73c1/href">https://medium.com/media/1f04dc8d4d383ce14396e42942de73c1/href</a></iframe><p>This service knows how to create a user, log a user in, and fetch a user object. Something like fetching a user object for a given ID is something that is likely to be used in multiple places in an app, which is where service objects come in handy in keeping things DRY.</p><h3>Entity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*6UzkrgDdsaT17BOuciIfBQ.png" /></figure><p>Entity responsibilities:</p><ul><li>Represent data</li></ul><p>Entities are pretty straight forward and what you would expect. They embody some type of data and act as the “payload” that gets passed around between the other classes. For example, the data manager returns an entity to the interactor, which returns an entity to the presenter, which then uses that entity to tell the view what it should display.</p><h3>Router/Wireframe</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*oULn94oeeGrlZfAf_HJ27A.png" /></figure><p>Wireframe responsibilities:</p><ul><li>Initializes all the other classes</li><li>Handles routing to other views in the app</li></ul><p>The router/wireframe is what glues all of the other VIPER components to one another and handles navigating from one view to another in the app.</p><h4>Initializing all the other classes</h4><p>You might be wondering how all of these VIPER classes get instantiated and wired up to talk to one another. That’s where the router/wireframe comes in.</p><p>In VIPER, every “stack” consists of a view, presenter, interactor, data manager and services (for us anyways), and entities. This “stack” is what VIPER refers to as a <em>module</em>. A VIPER module should correspond to a single <em>use case. </em>A use case is some function your app should perform for the user.</p><p>For example, one use case that is common for many apps is allowing the user to log in with an account. For this, we would have a VIPER module specifically for the “Log in” screen of the app. This module would have:</p><ul><li>A view that displays the “Log in” screen.</li><li>A presenter that handles events like the user requesting to log in with a specific username and password.</li><li>An interactor that knows what methods to call on the data manager for such events like attempting to log the user in.</li><li>A data manager that knows what services to use to retrieve or send information to the server.</li><li>Services that know what HTTP URLs to make requests to.</li><li>Entities that your server responses are converted into so that the information is useful in your app.</li></ul><p>As you’ll notice, the view, presenter, interactor, and data manager are very specific to this module. That is, they only know how to deal with things related to logging in. The services and entities on the other hand are very general things that can be used throughout many different modules. In this case, the service might be one that knows how to hit all the endpoints related to Users on your server. This might include logging in, signing up, or just retrieving general User data. Then entity you might use here would be a User entity, which just represents a User object. It’s easy to see that this entity can be used in many places in your app.</p><p>Now that we’ve explained what a VIPER “stack” or <em>module </em>is, we can explain part of the responsibility of the wireframe. The wireframe is what instantiates instances of each of these VIPER components and wires them up to talk to each other. That is, it gives the view and presenter references to one another, the presenter and interactor references to one another, and so on. Instantiating a wireframe is equivalent to instantiating an entire VIPER module.</p><h4>Handling routing to other views in the app</h4><p>The wireframe’s other alias, router, is what makes up the <strong>R </strong>in VIPER. The wireframe knows how to navigate to and present other modules when requested. This means the wireframe will also have references to other wireframes.</p><p>For example, suppose you have an initial screen in your app that is your typical home screen for an app that requires user accounts. This screen would have a button for “Sign up” and a button for “Log in”. This screen is a module; let’s call it the registration prompt (naming is hard). The use case here is that the user should be able to see their options before being logged in to your app. When the user presses the “Log in” button, the typical flow is:</p><ul><li>The view will notify the presenter that the user has requested the log in prompt.</li><li>The presenter will realize this requires a separate module so it will notify the wireframe.</li></ul><p>Now, the registration wireframe will instantiate the log in wireframe, thereby instantiating an entire VIPER module, and present the log in view over the registration view (maybe as a modal).</p><h3>Benefits of VIPER</h3><p>After using VIPER, we’ve found it to be very beneficial in many ways. Let’s get back to the list of things we set out to accomplish when architecting our app to see if VIPER addresses them.</p><ul><li>Easy to iterate on</li><li>Collaboration friendly</li><li>Separated out concerns</li><li>Spec-ability</li></ul><h4>Easy to iterate on</h4><p>One thing that is very helpful in adding features to an app is knowing where new code should live in relation to the old code. VIPER does a good job of this with each of its components having a clear set of responsibilities that doesn’t bleed into one another, which makes it easy to decide where to put new code.</p><p>I often find that when I’m adding new features to a module, it almost feels like an everyday routine because I already know where each piece of code should be placed and it’s just a matter of getting it done.</p><p>That being said, we do run into situations in VIPER where we’re unsure of where to place some piece of code and we have to make a judgement call. For example, if the user can select multiple items in a list before performing some action on them all, should we keep this state in the view, presenter, or another other class in the VIPER stack? Once you figure out what makes most sense to you, you can bypass these problems in the future easily because you’ve solved them already. Then everything becomes routine again.</p><h4>Collaboration-friendly</h4><p>VIPER makes working in a team surprisingly easy. Because use cases are separated into different modules, you don’t step on other people’s toes since all the code for one feature is usually compartmentalized into its own module.</p><p>In practice each of the VIPER components interact with one another via an interface. In objective-C this is just a protocol. The nice thing about this is that you can define the interface between two classes and then separate people can work on those classes individually. We’ve had much success with this by defining the view-presenter interface ahead of time and having one person work on the view doing purely UI work and another person work on the rest of the VIPER stack doing purely “backend” work.</p><h4>Separated concerns</h4><p>With each VIPER module abiding by the Single Responsibility Principle, VIPER naturally separates out concerns among classes. This is what makes the former two points (and the last point) work out so nicely.</p><h4>Easy to test</h4><p>By having separate components that follow the Single Responsibility Principle, this also makes things easy to spec. It gives you the ability to spec specific functionality while stubbing out other dependencies. For example, if you want to test your interactor logic, all you have to do is stub out the presenter and the data manager to eliminate the dependencies that can make writing specs complicated. Then your specs will only be testing the interactor and you can write separate specs for the presenter and data manager.</p><h3>Conclusion</h3><p>Overall we’ve found making the switch to VIPER to be very helpful and beneficial to us for the reasons mentioned above. There are of course many obstacles you will encounter in using VIPER that will require you to mold VIPER to your needs, but that is true of any architecture you choose to go with.</p><p>I would definitely recommend others to try out VIPER and also to take a look at the other blog posts on it. Hopefully this post has been helpful and gotten some of you excited to try out VIPER.</p><p>Additional Reading:</p><ul><li><a href="http://mutualmobile.github.io/blog/2013/12/04/viper-introduction/">Introduction to VIPER</a></li><li><a href="http://www.objc.io/issue-13/viper.html">Architecting iOS Apps with VIPER</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36ef1601a41f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brigade-engineering/brigades-experience-using-an-mvc-alternative-36ef1601a41f">Brigade’s Experience Using an MVC Alternative</a> was originally published in <a href="https://medium.com/brigade-engineering">Brigade Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>