<?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 Vivek Thakur on Medium]]></title>
        <description><![CDATA[Stories by Vivek Thakur on Medium]]></description>
        <link>https://medium.com/@vivekthakur647?source=rss-78db55c130b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YWXowgjkWFOKQV7q.</url>
            <title>Stories by Vivek Thakur on Medium</title>
            <link>https://medium.com/@vivekthakur647?source=rss-78db55c130b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:56:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vivekthakur647/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[Top IOS Interview Questions and Answers]]></title>
            <link>https://medium.com/@vivekthakur647/top-ios-interview-questions-and-answers-f92d4b5ca735?source=rss-78db55c130b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f92d4b5ca735</guid>
            <dc:creator><![CDATA[Vivek Thakur]]></dc:creator>
            <pubDate>Fri, 13 Dec 2019 18:26:49 GMT</pubDate>
            <atom:updated>2019-12-13T18:27:58.610Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Q1. What is method swizzling, where have you used it?</blockquote><p>Ans: Method swizzling is the process of changing the implementation of an existing selector. It’s a technique made possible by the fact that method invocations in Objective-C can be changed at runtime, by changing how selectors are mapped to underlying functions in a class’s dispatch table.</p><p>Reference:</p><p><a href="https://www.uraimo.com/2015/10/23/effective-method-swizzling-with-swift/">https://www.uraimo.com/2015/10/23/effective-method-swizzling-with-swift/</a></p><p><a href="https://nshipster.com/method-swizzling/">https://nshipster.com/method-swizzling/</a></p><blockquote>Q2. What is the code review process , what all are the main things which you consider during reviewing swift based iOS application?</blockquote><p>Ans: There is no perfect answer, but you can try to cover as much as possible like memory footprint, app performance, optionals etc.</p><p>Delegates implemented in extensions</p><p>Are all methods that should be private, file private or final</p><p>Is the use of optionals minimal or Properly handled</p><p>Is the use of ! forced unwrap rational and not crash-able.</p><p>Use of Any or AnyObject should be minimal. Use specific types or protocols. Or even better use generics</p><p>Are only methods public that need to be tested</p><p>Are there any classes that seem overly long? Maybe some functionality should be split into separate classes.</p><p>Is the app compiled with <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html">ARC, MRR</a>, or a mix? If not all ARC, why not</p><p>Does the app make good use of common Cocoa patterns, such as <a href="https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html">MVC</a>, <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html">notifications</a>, <a href="https://developer.apple.com/library/mac/documentation/cocoa/conceptual/KeyValueObserving/KeyValueObserving.html">KVO</a>, lazy-loading, etc? Are there any efforts underway to adopt patterns that aren’t backed by Apple, but are gaining steam in the iOS world, such as <a href="https://github.com/ReactiveCocoa/ReactiveCocoa">Reactive Cocoa</a> and<a href="http://www.teehanlax.com/blog/model-view-viewmodel-for-ios/">MVVM</a>?</p><p>Are there view-controllers that are overloaded with too much responsibility?</p><p>Check for static dispatch and dynamic dispatch</p><blockquote>Q3. What is the unit testing framework for iOS app, Have you used it?</blockquote><p>Ans: Some of the popular Test Frameworks for IOS application.</p><p>Appium : is an open-source testing tool. It provides automations of application testing process on Android and IOS. It allows the user to check each individual parts of the program’s source code, and systematically done during the process of programming.</p><p>Calabash : is an IOS automation testing tool. The testing process of this framework is done based on <a href="https://cucumber.io/">Cucumber</a> (an extensive automation testing tool)</p><p>XCTest : is the IOS functional testing framework. This framework can be used for testing at any state of the development process.</p><p>EarlGrey : is the best UI testing framework. This open-source framework is easy to integrate with IOS.</p><p>Jest : is an automated testing framework. Using this framework, we can ensure that the user interface cannot be changed unexpectedly.</p><blockquote>Q4. What is Mocking?</blockquote><p>Ans: Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.</p><p>In short, mocking is creating objects that simulate the behavior of real objects.</p><p>Reference: <a href="https://www.raywenderlich.com/1752-unit-testing-tutorial-mocking-objects">https://www.raywenderlich.com/1752-unit-testing-tutorial-mocking-objects</a></p><blockquote>Q5. Tell me about generics in swift , where have you used?</blockquote><p>Ans: Generic functions can work with any type. Please refer <a href="https://docs.swift.org/swift-book/LanguageGuide/Generics.html">https://docs.swift.org/swift-book/LanguageGuide/Generics.html</a> for more details.</p><p>Q6. Difference between UICollectionViewDelegateFlowLayout UICollectionViewFlowLayout?</p><blockquote>Ans: UICollectionViewFlowLayout : A concrete layout object that organizes items into a grid with optional header and footer views for each section.</blockquote><p>The UICollectionViewDelegateFlowLayout protocol defines methods that let you coordinate with a UICollectionViewFlowLayout object to implement a grid-based layout. The methods of this protocol define the size of items and the spacing between items in the grid..</p><blockquote>Q7. What is the benefit of CoreData over Sqlite?</blockquote><p>Ans:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*KpCR4tNpPKx3d71oktp-dg.jpeg" /></figure><blockquote>Q8. What are the different ways to achieve concurrency in iOS?</blockquote><p>Ans: iOS Concurrency: NSOperation and Dispatch Queues</p><p><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ConcurrencyandApplicationDesign/ConcurrencyandApplicationDesign.html#//apple_ref/doc/uid/TP40008091-CH100-SW1">Concurrency and Application Design</a>introduces the basics of asynchronous application design and the technologies for performing your custom tasks asynchronously.</p><p><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationObjects/OperationObjects.html#//apple_ref/doc/uid/TP40008091-CH101-SW1">Operation Queues</a> shows you how to encapsulate and perform tasks using Objective-C/Swift objects.</p><p><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW1">Dispatch Queues</a> shows you how to execute tasks concurrently in Swift/ObjectiveC/ C-based applications.</p><p><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html#//apple_ref/doc/uid/TP40008091-CH103-SW1">Dispatch Sources</a> shows you how to handle system events asynchronously.</p><p><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW1">Migrating Away from Threads</a>provides tips and techniques for migrating your existing thread-based code over to use newer technologies.</p><blockquote>Q9. What is SSL Certificate, Where do we use it , Have you ever used it?</blockquote><p>Ans: SSL Provides Authentication</p><p>In addition to encryption, a proper SSL certificate also provides authentication. This means you can be sure that you are sending information to the right server and not to an imposter trying to steal your information.</p><p>Reference: <a href="https://www.sslshopper.com/why-ssl-the-purpose-of-using-ssl-certificates.html">https://www.sslshopper.com/why-ssl-the-purpose-of-using-ssl-certificates.html</a></p><blockquote>Q10. What is the difference between Delegate and Notification?</blockquote><p>Ans: The <a href="https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html">concept of delegation</a> as its name suggests allows an object to send a message to another object (the delegate) so that it can customise the handling of an event.</p><p>The <a href="https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/Notification.html">concept of notification</a> differs from delegation in that it allows a message to be sent to more than one object. It is more like a broadcast rather than a straight communication between two objects. It removes dependencies between the sending and receiving object(s) by using a notification center to manage the sending and receiving of notifications. The sender does not need to know if there are any receivers registered with the notification center. There can be one, many or even no receivers of the notification registered with the notification center.</p><p>The other difference between notifications and delegates is that there is no possibility for the receiver of a notification to return a value to the sender.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f92d4b5ca735" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyze iPhone X]]></title>
            <link>https://medium.com/@vivekthakur647/analyze-iphone-x-vivek-thankur-755f9d14c787?source=rss-78db55c130b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/755f9d14c787</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[iphone-x]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Vivek Thakur]]></dc:creator>
            <pubDate>Fri, 15 Sep 2017 04:18:38 GMT</pubDate>
            <atom:updated>2023-04-06T10:35:09.287Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.facebook.com/btheme">https://www.facebook.com/btheme</a><br><a href="https://www.youtube.com/channel/UCafPBLvZlAqQ4alRDvFMXJw?view_as=subscriber">https://www.youtube.com/channel/UCafPBLvZlAqQ4alRDvFMXJw?view_as=subscriber</a></p><h3>Design for iPhone X</h3><p>The iPhone X (<em>read: iPhone ten</em>) is officially here, well it will be on November 3rd. It rocks an edge to edge Super Retina Display with a resolution of 1125×2436px. It also has a cut-out at the top of the screen where you can find some futuristic face unlock features.</p><p>Designing for this beautiful machine will bring some new challenges, but also some new design opportunities. The width of the device in portrait mode is the same as the iPhone 6, 7 and 8, but is 145pt taller, which results in ± 20% more vertical space. When designing @ 1x you need an artboard of 375×812px. You won’t export images @ 2x like the iPhone 8, but @ 3x like the iPhone 7–8 Plus, because of the new Retina display.</p><p>When creating your design, you must make sure you don’t obscure your UI with the devices unique features (the round edges, the cut-out at the top and the home indicator). By the way, the home indicator is that small line that lives on the bottom of your screen, it replaces the physical home button. You swipe up from any app to go back to your homescreen or into multitasking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*7kAlcPK0mvTXnABNMN0D6w.png" /><figcaption>^ See that white line, that’s the new home indicator.</figcaption></figure><p>If you currently have an app that uses iOS native component you will be fine and your app will already be adapted for this new iPhone. This can be navigation bars, tables, collection views and tab bars. They will be automatically inset and positioned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kS_0HCmD9HY0CnmmJrrgAQ.png" /><figcaption>^ iPhone 8 design on the left, automatically adapted to the iPhone X on the right</figcaption></figure><p>If you use custom layout, your app might need to be updated to the new screen layout. If you use Auto Layout however, that might be fairly easy.</p><h3>Let’s get started</h3><p>First off, embrace the devices design, Apple employees didn’t work this hard for you to hide the wonderful features of this expensive piece of hardware.</p><p><strong>Make sure you create a full screen experience. </strong>Let scroll views scroll to the very bottom of the screen even beyond the edges of the curved bottom of the display. Apple also kindly asks you not to hide the cut-out at the top and the curved edges at the bottom, so don’t go placing black bars to make it look like a regular old school iPhone 8.</p><p><strong>Center and inset important information.</strong> Make sure that important content is aligned in the center and use symmetrical insets, so your UI doesn’t get clipped by the device’s sensors or corners. If you use Auto Layout, your content will automatically be placed within a safe area so your design won’t be hidden behind the corners, sensors or the home indicator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*qlTFQRv0PJM4OVasU5Qu6A.png" /></figure><p><strong>The new status bar.</strong> Because of the sensors on top of the display, the new status bar is split in 2 parts. If your UI is doing something special with that space (previously 20pt high, now 44pt), you will need to update your interface because it will be taller on the iPhone X. Make sure that it can be dynamically changed in height. A great thing is that the height won’t be changed if a user makes a phone call or is using a navigation app, which was previously the case on other iPhones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*AgNyOR30P-xcv_Z_rdK8iw.png" /><figcaption>^ split and taller status bar</figcaption></figure><p><strong>Show off the new status bar.</strong> If you currently hide the statusbar in your design, Apple asks you to reconsider this decision. Since the screen is taller and you have more estate to display your content it might be use full to unhide that status bar. Users can find useful information up there and the space will most of the time not be used by other UI elements.</p><p><strong>Full screen images.</strong> If you are currently using full screen images in your design, you will need to update them for the new iPhone. They might be cropped and an essential part of the visual might be hidden.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7FpwkZG7DalV7RKcrXwvQ.png" /></figure><p><strong>Don’t place interactive controls at the bottom of the screen.</strong> The spacing around the home indicator is purely created for gestures, swipe up to go home. Placing buttons near this indicator or in the bottom round corners of the display might not be great. Users might accidentally use the home gesture and your UI will be difficult to reach. You can however still use tab bars and function bars, but keep in mind that they should not interfere with the home indicator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*tKg9MXO7pRNU3yQG9fRJFQ.png" /></figure><p><strong>Don’t hide the home indicator (all the time). </strong>iOS makes it possible to hide the home indicator in your app, this will auto-hide it when the user doesn’t touch the screen for a few seconds. It will reappear when the user touches the screen again, this should be mainly used for immersive experiences like viewing videos or photos. The home indicator will also change color automatically based on the background of your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*f0le-N7FndRqMDIM4gf1_A.png" /></figure><p><strong>More colors.</strong> The new Super Retina Display displays more colors, P3 color instead of sRGB. This means that it will show richer and more saturates colors. Especially video and photos will benefit of this wider color range.</p><p><strong>Swipe up, be mindful with the use of gestures.</strong> Since the physical home button is gone, you interact with your iPhone (more than ever) by using gestures. When you swipe up you go home or go to the multitasking view. When swiping left and right on the home indicator, you switch between your open multitasking apps. By swiping down from the top of the screen, you go to your Notification or Control Center. More so in games, you can use custom gestures that may override the native iOS gestures. You can use your own gestures by implementing “edge protect” which is a feature the will prefer the app’s specific gesture first, before the OS gesture, only one time though. Use this sparingly, because it will make it harder for your user to use system features.</p><p><strong>Face ID.</strong> Previous iPhone has a great feature Touch ID, which allowed users to unlock their device or perform password locked actions inside apps by using their fingerprint. This sensor was hidden inside of the home button, since it has gone in the iPhone X, Apple replaced it with a more advanced and secure way of unlocking your device. Enter Face ID, it uses some really great algorithms to detect your face and unlock your device. This will show some new UI in apps, make sure you implement it for your (rich) users that have an iPhone X. Also make sure that you don’t reference to Touch ID anymore in your onboarding or menu, replace it with Face ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*OdWPWdHVmNC4vOua4afQmw.png" /></figure><p><strong>Custom keyboards.</strong> When you are designing a custom keyboard, you shouldn’t add an Emoji or dictation button to your keyboard. Because it will automatically be added underneath the keyboard around the home indicator.</p><p><strong>Larger navigation bars.</strong> With iOS 11 the design of the native navigation bars got an update, they are now way taller. This design will especially be great on the taller iPhone X and will blend nicely with that new status bar. So consider using it in your design. These will also have some nice native animations when scrolling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*RqZrnSmdhY9ynyY4NsPTwA.png" /></figure><h3>TL;DR</h3><ul><li>The iPhone X is <strong>145pt taller</strong>, so design for <strong>375×812pt</strong> instead of <strong>375x667pt</strong></li><li>The iPhone X uses <strong>@ 3x</strong> <strong>assets</strong>.</li><li>Create a <strong>fullscreen experience</strong>, don’t hide the devices unique features.</li><li><strong>Center</strong> the <strong>importent content</strong> of your UI, to make sure it’s always visible and not hidden by the device’s sensors or corners.</li><li>A <strong>new</strong> taller split-in-two <strong>statusbar</strong>, previously 22pt, now 44pt high.</li><li><strong>Fullscreen images</strong> might/should be updated to be fully displayed.</li><li><strong>Don’t add buttons</strong> at the bottom of the screen, near the home indicator.</li><li><strong>Don’t hide</strong> the <strong>home indicator, </strong>only when really necessary.</li><li><strong>Richer and more saturated colors</strong> thanks to the P3 color spectrum.</li><li>Be aware for <strong>custom gestures </strong>near the home indicator and status bar, don’t mess with the user’s expected native gestures.</li><li><strong>Face ID</strong> replaces Touch ID, update your UI and replace textual references to Touch ID.</li><li><strong>Custom keyboards</strong> don’t need to add the Emoji and dictation buttons.</li><li><strong>Larger navigation bars</strong> will look and animate great on this tall display.</li></ul><p><em>Or watch Apple’s video on Designing for iPhone X.</em></p><h4>How do I preview my app UI?</h4><p>You can use the Xcode 9 simulator the preview your app, this will immediately show you if your UI needs to be updated.</p><h4>Where can I find iOS 11 and iPhone X resources?</h4><p>You’re lucky, Apple has some great new resources for Sketch, Photoshop and Adobe XD. You can find them here: Apple Design Resources.</p><p>Note: most of this information comes from the Apple UI Guidelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=755f9d14c787" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iPhone X: The first true @3x device]]></title>
            <link>https://medium.com/@vivekthakur647/iphone-x-the-first-true-3x-device-f39713d8bd4c?source=rss-78db55c130b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f39713d8bd4c</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[iphone]]></category>
            <category><![CDATA[pinterest]]></category>
            <category><![CDATA[iphone-x]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Vivek Thakur]]></dc:creator>
            <pubDate>Fri, 15 Sep 2017 04:14:08 GMT</pubDate>
            <atom:updated>2017-09-15T04:14:08.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>iPhone X: The first true @3x device</h3><p>Well the long rumored iPhone X is officially unveiled and it comes with a laundry list of extremely impressive specs. One of the most interesting things to note though is the new 5.8 inch “<em>Super-Retina</em>” display. It has a screen resolution of 1125px × 2436px. This is a particularly interesting resolution choice since according to Apple’s Human Interface Guidelines it’s an @3x screen with an effective 375 x 812 visual points of screen available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-GGR3JgEDety4d2uWqIIw.png" /><figcaption>iPhone 6/6S/7 left, iPhone X right via Human Interface guidelines</figcaption></figure><p>Basically what this means for user’s is they’ll get the same content they were getting before on an iPhone 6 sized device just with 20% additional screen height and a bump from @2x resolution to @3x.</p><p>You may be thinking well what about Apple’s iPhone plus (6+, 6S+, 7+, 8+) line? Those have been “<em>true</em>” @3x devices for years now right? Well not quite. Following Paintcode app’s “<em>Ultimate Guide To iPhone Resolutions</em>” which has been updated to include the new iPhone X the 6 Plus takes a @3x effective resolution than downsamples it to fit the physical pixels on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*vysYQoG5R1dqDC_-d7JQAA.png" /></figure><p>What this means for user’s is this is the first device that they will truly see the full visual fidelity of @3x elements on their screens. For developers it means now is as good a time as an any to jump on the @3x support bandwagon. It’s likely you are already providing @2x and @3x versions of your assets though in which case you’re all set for supporting the full display capabilities of the iPhone X.</p><p>For flat/simple vector assets its recommended to bring them into Xcode as PDF’s and let Xcode scale these into 1x/2x/3x assets for you. Starting with Xcode 9 this is easier than ever to use since there is a new option to preserve vector data. That means not only can it handle scaling for different devices but your assets can be upsized or downsized without any loss in quality.</p><p>The iPhone X represents a significant departure from Apple’s strategy for the last couple of years of delivering iterative improvements with minimal design changes to their flagship device. What are your thoughts on supporting this device in your app’s going forward?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f39713d8bd4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Swift]]></title>
            <link>https://medium.com/@vivekthakur647/reactive-swift-27a914fcc19a?source=rss-78db55c130b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/27a914fcc19a</guid>
            <category><![CDATA[reactive]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Vivek Thakur]]></dc:creator>
            <pubDate>Wed, 16 Aug 2017 05:12:22 GMT</pubDate>
            <atom:updated>2017-08-16T05:16:37.664Z</atom:updated>
            <content:encoded><![CDATA[<h3>Subscribe on youtube : <a href="https://www.youtube.com/channel/UCafPBLvZlAqQ4alRDvFMXJw">https://www.youtube.com/channel/UCafPBLvZlAqQ4alRDvFMXJw</a></h3><p><a href="https://twitter.com/vivekTios">https://twitter.com/vivekTios</a></p><h3>Reactive Swift</h3><h4>My journey with reactive programming in Swift — and the iOS app that came out of it.</h4><blockquote>UPDATE: ReactiveCocoa‘s new Swift API is out now.</blockquote><p>Let’s go back in time to when Apple introduced Swift, the successor to good old Objective-C, it was a very different time. Siri hadn’t yet opened the gate to Hades, Prezi wasn’t available on a monthly subscription, and North Korea hadn’t hacked anyone’s emails. I myself was extremely excited about having a new language on the table, especially one with a background in scripting languages, but still type-safe. Although Swift has grown rapidly ever since, we don’t yet consider it production ready. When that time comes, I want to be familiar with how to deliver clean, testable code…with a reactive UI (if I could have any wish)? Well, read on, if you’re interested in something besides the ordinary Objective-C &amp; MVC world.</p><h3>MVC vs. MVVM</h3><p>Let’s start from zero. When designing an application you probably start by considering the architecture you want to build.<a href="https://developer.apple.com/technologies/ios/cocoa-touch.html"> Cocoa</a> comes with<a href="https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html"> Model-View-Controller</a> (alias MVC), see my most favourite ever diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*pEvMKHBK9HeAgrYC." /></figure><p>Although you might not find this architecture efficient for your design, we can see in the picture, the <em>controller</em> rules everything (the clue is in the name). If you have experience with MVC on iOS/Mac, I bet you’ve already seen <em>view controllers</em> responsible for a lot more than you wanted in the first place. The more you work with MVC, the sooner you’ll face the fact that you have to figure out a different way of solving your problems. When it comes to handling network communication methods — which is not exactly black magic nowadays — you’ll end up just like Thomas the Tank Engine, working a big <a href="http://en.wikipedia.org/wiki/The_Fat_Controller">fat controller</a>, responsible for getting the data from all sources and rendering them to the UI at the same time. Even worse, have you ever tried to cover a <em>view controller</em> with<a href="http://en.wikipedia.org/wiki/Unit_testing"> unit tests</a>? Painful stuff for sure, having a <em>view</em>involved in tests, testing the presentation logic. With the <em>view</em>’s complexity growing, it’s just not worth the effort. That’s why people usually don’t test <em>view controllers</em> inside MVC.</p><p><a href="http://www.objc.io/issue-13/mvvm.html">Model-View-ViewModel</a> (MVVM) though, can be better for your app’s design for a lot of reasons. It comes from Microsoft and is a powerful architectural pattern for event-driven implementations. As you can see, here the <em>view</em>owns the <em>view model</em>, unlike the MVC case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*SUaY1aSgIcvDys9j." /></figure><p>Naturally, it depends on what are you working on and how you’d like to scale it, but at the end, it means less complexity and better testable code. At the same time? How is that possible? It’s all about moving logic to the <em>view model</em> and reducing the responsibility of the <em>view controller</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*HDQw_v9_d_f6x4Xd." /></figure><p>Allow me to use one of my pet projects as an example to introduce you to the concept. It’s the iOS client of a semi-automated brewing machine that helps reach and hold temperature levels during the brewing process (extremely important work). If you want to read more about the topic, check out this article about the <a href="http://blog.risingstack.com/brewfactory-full-stack-homebrew-with-iot/">home brewer</a>. The point is, we would like to see the temperature — amongst other information — of the current brew all the time within the app.</p><p>Let’s get back to MVVM, and the temperature we were looking for. To be able to continuously read that value, we will use<a href="https://www.websocket.org/"> WebSocket</a>with our server and an MVC app for showing it on an iPhone. At first, we need a Brew <em>model</em> with the desired temperature stored in it.</p><pre>class Brew {<br>    var temp = 0.0<br>}</pre><p>We also need a Brew <em>view controller</em>, showing the temperature of the beer we are currently brewing.</p><pre>class BrewViewController: UIViewController {<br>    @IBOutlet weak var tempLabel: UILabel!<br>}</pre><p>In the old <strong>MVC</strong> way, we would implement the network logic inside the <em>view controller</em> and update the UI accordingly.</p><pre>socket.on(&quot;temperature_changed&quot;, callback: {(AnyObject data) -&gt; Void in<br>    self.brew.temp = data[0] as Float<br>     dispatch_async(dispatch_get_main_queue(), {<br>       self.updateTempLabel()<br>     })<br>})</pre><p>And that’s how we update our UI:</p><pre>func updateTempLabel() {<br>       self.brewLabel.text =  NSString(format:&quot;%.2f ˚C&quot;, self.brew.temp)<br>    }</pre><p>Well, we have everything in one place now, pretty awesome, isn’t it? No it’s not.</p><p>Imagine the case when you have to authenticate a user first, or draw live charts, or handle input fields, then what? Check out the complete<a href="https://gist.github.com/vasarhelyia/70b2c3fae2bbe38c4a7a"> MVC example</a>. But now check how it looks in the <strong>MVVM</strong> style:</p><pre>var brew = Brew()<br>dynamic var temp: Float = 0.0 {<br>    didSet {<br>        self.brew.temp = temp<br>    }<br>}</pre><p>These are the variables to store inside the <em>view model</em>, they look a bit strange, but I couldn’t see how to make it less weird (and I also wanted to shed a negative light on this solution, maybe I’m kind of biased already). Anyway, let me know how would <strong>you</strong> do it! Now back to the socket:</p><pre>socket.on(&quot;temperature_changed&quot;, callback: {(AnyObject data) -&gt; Void in<br>   self.temp = data[0] as Float<br>})</pre><p>So the network logic has moved to the <em>view model</em>. But how to notify the <em>view</em> about the changes in the model?<a href="http://nshipster.com/key-value-observing/"> Key-Value Observing</a> (KVO) is our friend. Here’s how our <em>viewDidLoad</em> will look:</p><pre>self.brewViewModel.addObserver(self, forKeyPath: &quot;temp&quot;, options: .New, context: &amp;brewContext)</pre><p>So we need to observe the temperature somehow. For that, I used a separate field for the <em>view model</em>. You might be asking, why do we even care about having a Brew model inside the <em>view model</em>? I would say then, future Brew model could have different fields (hints on the screenshot above), and you might want to serialize it, send it over the network, or something. We need to have it’s state.</p><pre>override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer&lt;Void&gt;) {<br>        if context == &amp;brewContext {<br>            dispatch_async(dispatch_get_main_queue(), {<br>              self.updateTempLabel((change[NSKeyValueChangeNewKey]) as Float) <br>            })<br>        } else {<br>            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)<br>        }<br>    }</pre><p>Wow, that’s.. a lot? There comes a huge amount of boilerplate code with KVO implementation, but it’s still more lightweight than an application written in the MVC style, especially when we think of putting more and more complexity into our application — into our <em>view model</em>. You can read the<a href="https://gist.github.com/vasarhelyia/e4fa64096517ae966d01"> whole snippet</a> of the MVVM example.</p><p>Anyway, it’s much better, but I still have the feeling we can improve somewhere. Now that we understand that the key for representing mutable models in MVVM’s <em>view</em> is data binding, what can be better at carrying out our bindings than some reactive magic?</p><h3>Reactive programming</h3><p><em>“Reactive programming is programming with asynchronous data streams.”</em></p><p>If you are not familiar with this quote, I suggest to read the article about<a href="https://gist.github.com/staltz/868e7e9bc2a7b8c1f754">reactive programming</a> by<a href="https://twitter.com/andrestaltz"> @andrestaltz</a>, it’s a pretty cool introduction. Basically, in the reactive world, everything is a stream, even a stream of streams is a stream. Check out this picture, representing button clicks / touch events as a stream:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*JyZB_1WzJRNIY7o-." /></figure><p>And this <a href="https://www.youtube.com/watch?v=jyaLZHiJJnE">important safety message about streams</a>.</p><p>Look at our example this way: Consider the socket data as a stream of temperature values and the <em>UILabel</em> listening to it. Transforming them meanwhile is where the functional magic comes into the picture, operators like<a href="http://rxmarbles.com/#map"> <em>map</em></a>,<a href="http://rxmarbles.com/#merge"> <em>merge</em></a>,<a href="http://rxmarbles.com/#filter"> <em>filter</em></a> and a lot more, amazing! Let’s see how all of these work together in Cocoa.</p><h4>ReactiveCocoa</h4><p>When we plan to do some reactive programming with Cocoa, the most popular choice is to use<a href="https://github.com/ReactiveCocoa/ReactiveCocoa"> ReactiveCocoa</a> (aka RAC) by GitHub. ReactiveCocoa is an<a href="http://en.wikipedia.org/wiki/Functional_reactive_programming"> FRP</a> inspired powerful data binding framework.</p><p>It operates with<a href="https://github.com/ReactiveCocoa/ReactiveCocoa/blob/master/Documentation/FrameworkOverview.md#signals"> signals</a>, which are defined as push-driven streams. It means, that a signal is a representation of an asynchronous flow that will deliver data or any kind of result to it’s subscribers in the future. In addition to modelling changes with signals, RAC also provides built-in UIKit/AppKit bindings, like<a href="https://github.com/ReactiveCocoa/ReactiveCocoa/blob/ee85a34731382b01ea028026ef267b0952b7edde/ReactiveCocoa/NSControl%2BRACTextSignalSupport.h#L22"> <em>rac_textSignal</em></a> and a lot of<a href="https://github.com/ReactiveCocoa/ReactiveCocoa/blob/master/Documentation/FrameworkOverview.md"> other helpful stuff</a>.</p><blockquote>All the code in this article uses RAC 2.4, but there is already a <a href="https://github.com/ReactiveCocoa/ReactiveCocoa/releases/tag/v3.0-RC.1">release candidate for the 3.0</a> of ReactiveCocoa. Check out my new post about how I turned this <a href="http://blog.alltheflow.com/reactive-swift-upgrading-to-reactivecocoa-3-0/">app using ReactiveCocoa 3</a>, if you are interested in upgrading.</blockquote><p>Except for some tiny details, like having <em>not</em> occupied and alike, you are able to write code with RAC 2.4.x in Swift. Also, Swift has built-in functional operators for its collection types, which comes handy all the time. No need for loops anymore!</p><p>Let’s see how can we build a<a href="https://github.com/ReactiveCocoa/ReactiveViewModel"> ReactiveViewModel</a> for our app, using ReactiveCocoa as the binding system for the MVVM architecture. Our <em>view controller</em> looks a lot better now, see?</p><pre>self.brewViewModel.tempChangedSignal.map {<br>            (temp: AnyObject!) -&gt; AnyObject! in<br>            return NSString(format:&quot;%.2f ˚C&quot;, temp as Float)<br>        } ~&gt; RAC(self.tempLabel, &quot;text&quot;)<br> }</pre><p>The <em>RAC</em> macro used in Objective-C before has been replaced, since C style complex macros are not available in Swift. Thank<a href="http://napora.org/a-swift-reaction/"> Yusef Napora</a> for the straightforward solution and<a href="https://twitter.com/colineberhardt"> @ColinEberhardt</a> for wrapping it up in his<a href="https://github.com/ColinEberhardt/ReactiveSwiftFlickrSearch">sample app</a>.</p><p>Now back to the brewing, it’s so reactive already! Let’s see the other end of the stream.</p><pre>socket.on(&quot;temperature_changed&quot;, callback: <br>    {(AnyObject data) -&gt; Void in<br>tempChangedSignal.sendNext(data[0]).deliverOn(RACScheduler.mainThreadScheduler())<br>    })</pre><p>Here, we are just creating signals of temperature data straight from the socket, and making sure the updating of the <em>UILabel</em> of the <em>view controller</em>will occur safely on the main thread. Ah, dammit, I can’t resist showing another example of how you can leverage the power of RAC. Now it comes with an HTTP request, handling the unfortunate error when trying to initiate a new brew on the server.</p><pre>NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler: {<br>                (response:NSURLResponse!, data: NSData!, error: NSError!) -&gt; Void in<br>                if error == nil {<br>                    subscriber.sendNext(JSON(data))<br>                    subscriber.sendCompleted()<br>                } else {<br>                    subscriber.sendError(error)<br>                }<br>})</pre><p>Here we send the received JSON to the subscribers on success and an <em>error</em>signal on failure. Handy, isn’t it?</p><pre>syncSignal.subscribeError({ (error: NSError!) -&gt; Void in<br>                UIAlertView(title: &quot;Error creating brew&quot;, message: error.localizedDescription, delegate: nil, cancelButtonTitle: &quot;OK&quot;).show()<br>})</pre><p>We just had to subscribe for the error events in the <em>view controller</em> and wait for the magic to happen when we, for example, lost connection.</p><h3>What was it all about?</h3><p>It was actually a real life example I brought up. I started with the plain old MVC version of the app, first in Objective-C. It was pretty straightforward, no surprises. Then Swift occurred, and I of course I fall in love with any such innovation whenever I see it and so decided to rewrite the entire app. After struggling a lot with the heavy controllers and my UI refresh mechanism, which I was not exactly proud of, I decided to go reactive. I was already familiar with the fact that it goes well with MVVM, so I gave it a try. The experience was like erasing half of my code. Then, transforming the app with ReactiveCocoa felt like doubling the value of the remaining half. Since then, adding tweaks (like changing a button’s state depending on some data) is basically writing an enabled signal to the button’s command, which is like writing one line of code, almost no effort. Think about how long it would take with the good old way.</p><p>There are <strong>so many</strong> other things you might wanna try out with ReactiveCocoa and with Swift as well. If you are interested in brewing some beer with this combination, or just the code itself, check out the full source of<a href="https://github.com/brewfactory/BrewMobile"> BrewMobile</a>, the iOS client of <a href="https://twitter.com/brewfactory">@brewfactory</a>. Are you aware of a technology to make the app even better, or just more delightful? Let me know! And of course, feel free to contribute.</p><p>And to end with, some insights about the future of BrewMobile, I’m looking forward to introducing <a href="https://facebook.github.io/react-native/">React Native</a> to brewing as soon as possible. I will of course share my experiences if React Native turns out to be all I think it might be.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27a914fcc19a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>