<?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 Emre Ergün on Medium]]></title>
        <description><![CDATA[Stories by Emre Ergün on Medium]]></description>
        <link>https://medium.com/@ergunemr?source=rss-7c04f0bf8f17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6Tz51bBg0vu1ptA7lPcdyw.png</url>
            <title>Stories by Emre Ergün on Medium</title>
            <link>https://medium.com/@ergunemr?source=rss-7c04f0bf8f17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 16:22:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ergunemr/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[Modular Event Tracker in Swift]]></title>
            <link>https://levelup.gitconnected.com/modular-event-tracker-with-swift-ce8425a06f64?source=rss-7c04f0bf8f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce8425a06f64</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[tracker]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[modular]]></category>
            <dc:creator><![CDATA[Emre Ergün]]></dc:creator>
            <pubDate>Sun, 19 Jul 2020 17:54:58 GMT</pubDate>
            <atom:updated>2020-07-25T15:06:10.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pT8Nnb0S4xQhrbPa3ZJ-Ow.png" /></figure><p>Almost every iOS app other than very small hobby projects have a tracker architecture to measure and track analytic events. Sometimes its enough to implement either third party solution or in-house tracking solution, sometimes you should support both of these. Besides just implementing them, for the sake of the project, you want to keep tracking mechanism tidy too.</p><p>Since Trendyol iOS app is one of the most popular iOS apps in Turkey at the e-commerce category, we use both varieties of third party solutions and an in-house solution too for event tracking. Actually we had a tracking mechanism which has been performing well until the last quarter, however we have noticed that it won’t scale enough and comes with some problems as app grows. First take a look at the previous tracking solution we want to change, to see what are the problems here.</p><p>Let’s start with Tracking Service;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/204833fbce9d05723a0c93c40f90c7f4/href">https://medium.com/media/204833fbce9d05723a0c93c40f90c7f4/href</a></iframe><p><strong>TrackingService</strong> is a basic enum that contains tracking options. As you can see, it consists of some of the popular third party solutions and one in-house solution named <strong>AwesomeTracking</strong>.</p><blockquote>Actual name of the in-house solution we use is not <strong>awesomeTracking</strong>, however for the privacy reasons let’s name it like that for now.</blockquote><p>Other than the TrackingService, there is a <strong>Trackable </strong>protocol, which <strong><em>every event</em></strong> should conform to it;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cd215062edf27bc44454c199ad62d00/href">https://medium.com/media/9cd215062edf27bc44454c199ad62d00/href</a></iframe><p><strong>Trackable</strong> protocol was heart of the tracking mechanism. As you can see, protocol has a required variable named <strong><em>services</em></strong> (which is explained above), and a <strong><em>track()</em></strong> method that it’s default implementation is provided at the Trackable extension.</p><p>In the track method, each event is sent via it’s associated instance (most of these are singleton objects). Its valid for in-house tracking mechanism, this statement is true for <strong><em>AwesomeTracking</em></strong> too. All the dirty event and networking stuff is hidden there.</p><p>To understand how it works at basic level, let’s implement a basic event named <strong>SupplierInfoEvent, </strong>since every event should conform to Trackable protocol, its implementation can be coded as;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/807a6685336cfb485cb3f9d7d0148af1/href">https://medium.com/media/807a6685336cfb485cb3f9d7d0148af1/href</a></iframe><p>As you can see, when you conform to <strong><em>Trackable</em></strong> protocol, you should implement <strong><em>services</em></strong> array which contains references of tracking services. In the spesific example event above, firebase is given to Trackable.</p><p>And you can send this event where ever you want with writing just one line of code;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46282be538cd4f83b40619945cd85863/href">https://medium.com/media/46282be538cd4f83b40619945cd85863/href</a></iframe><blockquote>Note that every event conforms Trackable implemented as an <strong>extension of Tracker</strong>, it’s just for seeing clearly which event are available when you write Tracker.xxx</blockquote><p>So, what was the problem here ? Why did we need to change it?</p><h3>Problems we have faced in the previous design</h3><h4>Reason #1 (Modularity)</h4><p>As Trendyol iOS app grows with very large features, we have decided to make it more modular app that consists of number of frameworks, packages etc. Besides large-scale features, Trendyol is aiming to become a super app that contains almost standalone app scale features like <strong>Dolap Lite</strong> (<em>online second hand fashion</em>) and <strong>Trendyol Go</strong> (<em>fast online grocery shopping</em>). Modularism was not taken into account while implementing this tracking mechanism since Trendyol iOS app is a whole monolith app at that time.</p><h4>Reason #2 (Testability)</h4><p>Since every event struct conforms to Tracking protocol and event sent through struct itself (no dependency injection), its hard to test current mechanism.</p><p>It would be great that mocking event structure while writing unit tests like “<em>if this method is invoked at the product detail screen, these two event method should be invoked too.”</em></p><h4>Reason #3 (Flexibility)</h4><p>Especially for the in-house solutions (mentioned as <em>AwesomeTracking</em> above), actual event sender class and Tracking service are coupled tightly. Besides that, concrete type is used instead of protocol type. For example, there are tons of default parameters sent each of the <strong>AwesomeTracking</strong> event, and these default parameters are handled at the actual event sender class (<strong><em>AwesomeTracking.shared</em></strong> instance for the current situation). Consider we will use AwesomeTracking in <strong>both Trendyol itself and Dolap Lite</strong>, however some of the default parameters<strong> should be different</strong>. What should we do in this case ? Since we can’t inject actual event sender class to Tracking Service, we should add new case for Dolap Lite’s AwesomeTracking service, which is sign of bad design.</p><h3>New Modular Design</h3><p>Our aim is to develop something that solves the problems mentioned above while preserving the positive aspects of the existing design.</p><p>Since we use this new tracking architecture in other frameworks by importing it, let’s create a framework named <strong>CoreTracker.</strong></p><blockquote>The reason behind the <strong><em>Core</em></strong> prefix in the name of this framework (and almost every file name in it) that it provides core level behavior for spesific tracking frameworks or targets that uses CoreTracker.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*91O8lqAxnei98LJ9L7hGPg.png" /></figure><p>After creating CoreTracker framework, let’s create <strong>CoreTrackable</strong> and <strong>EventService, </strong>these are almost like previous tracking implementation. CoreTrackable<strong> </strong>will be the protocol that <strong>each event should conforms to it.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1edebe0985cd0255579c3746cec8937a/href">https://medium.com/media/1edebe0985cd0255579c3746cec8937a/href</a></iframe><blockquote>Note that for keeping things simple, just one third party service <strong><em>(</em>firebase<em>) </em></strong>and one in-house service <strong>(awesome tracking) </strong>will be used.</blockquote><p>You should notice one difference here, at the previous implementation, <strong><em>track()</em></strong> method belongs to <strong>Trackable</strong> protocol (<em>aka CoreTrackable here</em>), however in the new design <strong>CoreTrackable</strong> only requires services array, which means track method not called through event itself, let’s put it to new protocol named <strong>CoreTracker.</strong></p><blockquote>CoreTracker will be the backbone of the our new event structure, each framework uses this event framework should define a concrete type that conforms to CoreTracker for sending events.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d75271b8177509b110f21fac2ca06afc/href">https://medium.com/media/d75271b8177509b110f21fac2ca06afc/href</a></iframe><p>You can see that at the line 10 and 12 there should be instances that actually <strong>send event</strong>. Since each framework uses CoreTracker framework would want to give it’s own event sending class, we should consider a protocol for them instead of concrete types.</p><p>For example for <strong>AwesomeTracking</strong>, we can create a protocol like below for project’s requirements;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f60be172dc06fd3781969ccc007eff1/href">https://medium.com/media/7f60be172dc06fd3781969ccc007eff1/href</a></iframe><p>In similar way, for third party service (<em>Firebase</em>) we can create a protocol to give actual event sending implementation to CoreTracker module;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81234cdbb20794d20a053c91fe60ea3b/href">https://medium.com/media/81234cdbb20794d20a053c91fe60ea3b/href</a></iframe><p>Now let’s put these two event services to CoreTracker protocol we have created before;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a88a21fa73094920aaa5a16b35c02a0/href">https://medium.com/media/0a88a21fa73094920aaa5a16b35c02a0/href</a></iframe><p>To visualize what we have done so far, we can take a look at the basic chart below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FY3_wpYYepNY1SCasIQVeg.png" /></figure><p>In summary, there is one <strong>CoreTracker</strong> protocol contains event services. When a framework want to use it, it should create a tracker class that conforms to CoreTracker, and as a requirement of CoreTracker<strong> </strong>it should give firebase service and awesome tracking service instances, which has to conform <strong>AwesomeTrackingService</strong> and <strong>FirebaseService protocols</strong>.</p><p>Now let’s use this event structure, consider second hand e-commerce feature embed into Trendyol app named <strong><em>DolapLite</em></strong> I mentioned above. It has its own frameworks in the project.</p><p>DolapLite consists of three interface frameworks, we called these as <strong><em>modules</em></strong>;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*sIlZgrplf8whPfR5dy7kEw.png" /></figure><p>If we want to use CoreTracker framework, we should create a <strong>Tracker</strong> class that conforms <strong>CoreTracker </strong>protocol. Since we want to use this Tracker in <strong><em>all interface frameworks of DolapLite</em></strong>, I should create a kind of wrapper framework and put Dolap Lite spesific Tracker class in it. So let’s create <strong>DLTracker</strong> (a.k.a DolapLite Tracker) framework and create tracker class in it after importing CoreTracker;</p><blockquote>Note that DL prefix is used for all classes belong to Dolap Lite</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be7972c6b6c65761f52be9202ad7b8ce/href">https://medium.com/media/be7972c6b6c65761f52be9202ad7b8ce/href</a></iframe><p>Since firebase service and awesome tracking service required parameters of CoreTracker protocol, we should create and set these two services.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca37c5352dadcde10b698587e61e50a0/href">https://medium.com/media/ca37c5352dadcde10b698587e61e50a0/href</a></iframe><p>The beauty of creating these services here that implementation of these services will be <strong>unique to Dolap Lite framework</strong>. It is required because parameters required for an event of Awesome Service in Trendyol and DolapLite would be <strong>different</strong>.</p><p>Let’s create <strong>DLTracker</strong> with these new services;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/545946c972151675b8c678e22319d411/href">https://medium.com/media/545946c972151675b8c678e22319d411/href</a></iframe><blockquote>Note that we have injected these services as default parameters of init method. Because while writing unit tests, we can init this tracker with mock services easily.</blockquote><p>Now we can use new tracker in one of the frameworks of Dolap Lite. Let’s import <strong>DLTracker</strong> framework and create a sample product detail event under <strong>DLProductDetail</strong> framework;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0970fe14c53a5cf99ac0673cdfc4e62d/href">https://medium.com/media/0970fe14c53a5cf99ac0673cdfc4e62d/href</a></iframe><p>After creating an event, consider using it in the presenter of dolap lite product detail page. Since all events should sent through an instance that conforms to <strong>CoreTracker</strong> protocol (<strong>DLTracker</strong> for Dolap Lite), let’s inject it to presenter object;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab51a37ecfa3d5cc002ac3414fc10097/href">https://medium.com/media/ab51a37ecfa3d5cc002ac3414fc10097/href</a></iframe><blockquote>Note that we retained tracker instance as a type of CoreTracker protocol, and injected DLTracker instance as default parameter of init. That because we can use mock tracker instance in the unit tests.</blockquote><p>Now sending event is easy task in that presenter;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29a68e0b00e1ff8b6c9588a95f9589b5/href">https://medium.com/media/29a68e0b00e1ff8b6c9588a95f9589b5/href</a></iframe><p>Lets re consider the problems mentioned at the first section with new tracking implementation;</p><h4>#1 Modularity</h4><p>New tracking mechanism capsulated into a single event framework and highly modular. If it is used in a different framework, importing and creating classes that conforms tracking protocols should be enough.</p><p>Also for third party services like firebase or adjust, their SDKs can be implemented at the tracker framework without bother the other modules.</p><h4>#2 Testability</h4><p>Event sending isn’t handled at the concrete event class itself, it is handled at the class that conforms to CoreTracker protocol, and since CoreTracker itself and it’s services can be injected through init, it is easily mockable and event sending is testable in the unit tests.</p><h4>#3 Flexibility</h4><p>Not only each framework that uses CoreTracker can provides its own services (for example DLAwesomeTrackingService in the Dolap Lite example), a previously created service can be reused in other frameworks too.</p><p>For example if firebase service implementation is same for Dolap Lite and Trendyol, we can create just one firebase service class and inject it to both <strong>DLTracker</strong> (Dolap Lite Tracker) and <strong>TYTracker</strong> (Trendyol Tracker).</p><p>We think this approach will solve our current problems so far, and we’ll use it until the next milestone. I hope you will find something useful from that too.</p><p>I hope you like it, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce8425a06f64" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/modular-event-tracker-with-swift-ce8425a06f64">Modular Event Tracker in Swift</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prefer Composition over Inheritance: Viper Module Case Study]]></title>
            <link>https://medium.com/trendyol-tech/prefer-composition-over-inheritance-viper-module-case-study-e64f626dc7e9?source=rss-7c04f0bf8f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/e64f626dc7e9</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[viper-architecture]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Emre Ergün]]></dc:creator>
            <pubDate>Wed, 08 Apr 2020 16:20:49 GMT</pubDate>
            <atom:updated>2020-04-08T16:20:49.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DSVv83v0wSRqC9TP" /><figcaption>Photo by <a href="https://unsplash.com/@momentsbygabriel?utm_source=medium&amp;utm_medium=referral">Gabriel Crismariu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello everyone, this story will be about couple of techniques we used in viper architecture, specifically avoiding code duplication while making module helper methods as reusable as it can be.</p><p>It is assumed that you are familiar with the Viper Architecture. If not, you may need to learn something about it first. There are plenty of resources since it is popular nowadays. 💪🏻</p><p>As you know, each layer in the viper module has an interface.</p><p>Assume that you have started a project and you decided to use VIPER as project architecture. Let’s say <strong>HomePage </strong>is your first module, then probably you want to create four layer-class (View, Interactor, Presenter and Router) and make implementations according to the VIPER. Let’s focus on the <strong><em>view layer (aka ViewController);</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c28ae6838620b335f3ee5329627c6aa9/href">https://medium.com/media/c28ae6838620b335f3ee5329627c6aa9/href</a></iframe><p>You defined public methods at the interface and implemented these methods at the place where your view controller conforms to the interface. Seems nice and clean, nice job. Then you started to next module, let’s say it is the <strong><em>ProductDetail</em></strong> Module. Like a view layer above, it’s view layer should be the something like below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c10c9f0b18d3caed649b7eb2439dd0b8/href">https://medium.com/media/c10c9f0b18d3caed649b7eb2439dd0b8/href</a></iframe><p>It looks nice too, but you have noticed an issue here. If you look at defined methods, some of them are defined exactly twice. Oh, there is some kind of duplication here. As a smart guy, you want to refactor it. Thankfully you know what <strong><em>object oriented programming</em></strong> is, and you have decided to apply it here.</p><p>Since each view layer is an instance of <strong><em>UIViewController</em></strong> in our example, you can remove these duplicated methods from view interfaces and define at the common <strong><em>UIViewController</em></strong> class. Let’s say it’s <strong><em>RootViewController</em></strong>;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/659fa9ed72205d29e314a4be97189b13/href">https://medium.com/media/659fa9ed72205d29e314a4be97189b13/href</a></iframe><p>Now you can make <strong><em>ProductDetailViewController</em></strong> and <strong><em>HomePageViewController</em></strong> inherit from the <strong><em>RootViewController</em></strong>. However it does not fit your current VIPER architecture since layers communicate each other <strong><em>using only layer interfaces</em></strong>. For example, for the HomePageModule, HomePagePresenter holds a reference of <strong><em>HomePageViewInterface</em></strong>, not the <strong><em>HomePageViewController</em></strong> itself. If you want to call <em>setTitle(_)</em> method from presenter, you will get a compile time error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4551d8c1831a6e066e6a313bb2ba57eb/href">https://medium.com/media/4551d8c1831a6e066e6a313bb2ba57eb/href</a></iframe><p>Actually it’s obvious, since <strong><em>HomePageViewInterface </em></strong>knows nothing about the RootViewController, methods you have implemented in the RootViewController are not accessible from presenter. How should you solve this ? Thanks to the swift, inheritance applies not only for classes, but also for <strong><em>protocols</em></strong>.</p><p>So, you have created a <strong><em>BaseViewInterface</em></strong> instead of BaseViewController for that purpose;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bc09d5334565a0ad64255930803e377/href">https://medium.com/media/3bc09d5334565a0ad64255930803e377/href</a></iframe><p>Then you conformed to <strong><em>BaseViewInterface</em></strong> for both <strong><em>HomePageViewInterface </em></strong>and<strong><em> ProductDetailViewInterface. </em></strong>There is one last step left. You should make default implementations of these methods at the <strong><em>BaseViewInterface extension;</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cf1dcacb514e7b038def9066b891c80/href">https://medium.com/media/2cf1dcacb514e7b038def9066b891c80/href</a></iframe><blockquote>You may wonder that why we use <strong><em>Self: UIViewController</em></strong> part. Its called protocol constraint, if you don’t add UIViewController constraint and try to use <strong><em>UIViewController</em></strong> related stuff here (for example <strong>navigationItem</strong> in the showLoading method), you’ll get an error. Because without UIViewController constraint, compiler cannot know which class actually conforms to this protocol when the program control reaches here. For further info, you can take a look at the <strong><em>Adding Constraints to Protocol Extensions</em></strong> part of the document you can reach using link below;</blockquote><p><a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html">Protocols - The Swift Programming Language (Swift 5.7)</a></p><p>It seems so far so good. Now there is no code duplication left, and you can add all common methods to BaseViewInterface in the future.</p><p>Is it perfectly okay ?</p><p>True, mostly. I am sorry to say that, however there is <strong><em>one last problem</em></strong> left. Actually it is not a problem, but as a smart developer, you can design it <strong><em>better</em></strong>. As the project gets bigger and bigger, <strong><em>BaseViewInterface</em></strong> will grow too. At some point, maybe you want to use just one method from <strong><em>BaseViewInterface, </em></strong>however by conforming BaseViewInterface<strong><em> </em></strong>you will apply many of unnecessary methods too. Clearly it does not fit to SOLID principles, especially in terms of separation of concerns.</p><p>Let’s focus on how we can make our design better. Actually, most of methods you defined at the <strong><em>BaseViewInterface </em></strong>can be grouped. For example, take a look at two methods defined at the BaseViewInterface;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da127b3a12d746641f87a0c42c02c4ad/href">https://medium.com/media/da127b3a12d746641f87a0c42c02c4ad/href</a></iframe><p>Each time a view layer should do something with urls, you can use these two methods. What about grouping these into a specific protocol instead of <strong><em>BaseViewInterface</em></strong> ? Let’s do this, remove these two methods with default implementations from BaseViewInterface to new protocol and call it <strong><em>UrlOpenable;</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efd6f035a5007478bf1699b6e242f588/href">https://medium.com/media/efd6f035a5007478bf1699b6e242f588/href</a></iframe><p>Now anytime you want to use these methods, you can simply make your class interface conforms to <strong><em>UrlOpenable</em></strong>. For example lets conform it for <strong><em>HomePageViewInterface</em></strong> we defined before;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8edf0a96bff529bd34e6fa7d1e667e57/href">https://medium.com/media/8edf0a96bff529bd34e6fa7d1e667e57/href</a></iframe><p>Now you can call <strong><em>openUrl</em></strong> method from <strong><em>HomePagePresenter </em></strong>through view<strong><em> interface. </em></strong>It will work well as before. We can create these task-specific methods as much as we need; <em>UrlOpenable</em>, <em>AlertPresentable</em>, <em>NavigationBarConfigurable</em>, <em>LoadingShowable</em>…</p><p>If you want to use a method from specific protocol, just conform it, super easy. In this way, you don&#39;t have to conform a god protocol for using just couple of methods. Actually, by making these changes, there should be no god protocol left 🙃</p><p>Thank you for reading, see you in the next story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e64f626dc7e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trendyol-tech/prefer-composition-over-inheritance-viper-module-case-study-e64f626dc7e9">Prefer Composition over Inheritance: Viper Module Case Study</a> was originally published in <a href="https://medium.com/trendyol-tech">Trendyol Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an iOS Viper Module — Step by Step Guide]]></title>
            <link>https://medium.com/trendyol-tech/creating-an-ios-viper-module-step-by-step-guide-cd1f414b7dd3?source=rss-7c04f0bf8f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd1f414b7dd3</guid>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[viper]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-architecture]]></category>
            <dc:creator><![CDATA[Emre Ergün]]></dc:creator>
            <pubDate>Mon, 28 May 2018 23:53:22 GMT</pubDate>
            <atom:updated>2018-05-29T18:38:16.987Z</atom:updated>
            <content:encoded><![CDATA[<p>What is VIPER ? What is VIPER Module ? How should a module be assembled?</p><h3>The Backstory</h3><p>Recently, as iOS development team we have decided to migrate our project codebase from Objective-C to Swift, also we have discussed the use of a new architecture instead of keeping all stuff in MVC.</p><p>So, open XCode, select file and new project, choose swift as development language and start over again, right ? 🤔</p><p>Nope, sometimes things are not so that easy. In fact, product managers would not be happy if whole team left new upcoming features as well as sprint goals to work on migration process. Therefore, we had to do both swift migration and common sprint jobs in parallel to make everyone happy. Apple call it <strong>Mix and Match</strong>, details can be viewed from link below,</p><p><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html">Using Swift with Cocoa and Objective-C (Swift 4.1): Swift and Objective-C in the Same Project</a></p><p>However this story is not about swift migration, also there are much better articles about it. If we focus on our decision about changing app architecture, what was the reason behind this ?Actually iOS project we have been working on was like a giant spaghetti in a pot that every developer add her/his own sauce to recipe for each new task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*FcbADM29YgsJaMc3mupL3w.jpeg" /></figure><p>So, which features should a good architecture provide?</p><ul><li>Easily followable data flow.</li><li>Each object has a clear role separated from others.</li><li>Easy to test.</li></ul><p>Truth is, our iOS project is lack of these features clearly.</p><p>Well, what are signs indicating there is a problem with app architecture ?</p><ul><li>Massive view controllers with thousands of lines of code.</li><li>Getting lost while debugging.</li><li>Increasing number of global variables all along the app.</li><li>Nearly impossible to test.</li></ul><p>Not surprisingly, these signs were defining our project. So, we have started to search for different architecture patterns used in iOS, with considering their pros and cons. After lots of reading, we have set a meeting to discuss with each other and make a final decision. At the end of the meeting, everyone seems to be satisfied with an architecture named <strong>VIPER </strong>to be our next.</p><h3>What is VIPER ?</h3><p>Viper is an architecture that divides a feature implementation into five distinct layer in one module. Each character of <em>VIPER</em> represents a different layer;</p><ul><li>V: View</li><li>I: Interactor</li><li>P: Presenter</li><li>E: Entity</li><li>R: Router</li></ul><p>Each layer has a distinct role in the module. In VIPER, I think implementing a feature like building a lego from different parts. Let’s take a look at each layer,</p><h4>View</h4><p>View is a dummy object receiving touch events most of the time. Instead of MVC’s massive view controller with thousands lines of codes, basically all service related codes and decision makings should not exist in it. For example, when a touch event was received from the user, view object should notify the presenter like <em>“My dear presenter, a touch was received from user and I don’t know what I should do with it”</em></p><h4>Presenter</h4><p>I think presenter is the heart of the VIPER module. Only layer in the module that communicates with all other layers. Basically all decision makings should be handled in the presenter. After the decision, presenter has to communicate with the layer required. For example, after notified by view with touch event, presenter should decide what should be done next. Does screen need to update it’s UI ? Then tell view layer to update UI with given info. Should a data be fetch from remove server ? Then tell interactor to fetch it. Similarly, does app need to navigate to other screen ? Then tell router to navigate which screen it is.</p><h4>Interactor</h4><p>Interactor contains business logic and it’s mostly responsible from api calls. It builds request from parameters and creates objects by mapping response. After finishing service connection, it notifies presenter like <em>“Hey presenter, these are puppies you are looking for”</em> or <em>“I’m sorry, I am not able to fetch your needs at this moment”</em>. You get the idea.</p><h4>Router</h4><p>You need segue to another module ? Tell router which module it should be presented next and leave the rest to it. Router needs a <strong>UINavigationController</strong> instance to do such navigation stuff. Also I think that router should be responsible for showing alerts since <strong>UIAlertController </strong>is used with <strong><em>present</em></strong><em> </em>method.</p><h4>Entity</h4><p>Plain data objects mainly driven by interactor. No more, no less.</p><p>To summarize, what a VIPER module should look like, take a look at the figure below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*rnmJYsedkv4jybUeQxJI4g.png" /><figcaption>Figure 1: Basic Viper Module Diagram</figcaption></figure><h3>Meet the Best iOS Demo App Ever</h3><p>Let’s convert something implemented in MVC to a viper module step by step. I created a very basic iOS app that consists of 3 screens which are <em>Home</em>, <em>AddressList</em> and <em>AddressDetail</em>. Home and AddressDetail are just dummy screens to provide integrity all around the app.</p><p>For example, let’s reimplement address list screen with VIPER. (Unit tests are skipped for now to make implementation short). Address list view controller simply presents addresses and if user clicks one of the addresses or add new address on the navigation bar, page navigates to address detail screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3kV-9rh8RGc5eyg4v4gc4Q.png" /></figure><p>Before start, take a look at the AddressViewController</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4762404de406786a776ced188bacc1b3/href">https://medium.com/media/4762404de406786a776ced188bacc1b3/href</a></iframe><p>As you can see, making service calls, presenting popups, triggering segues etc all are handled in view controller. It may seem not a problem in this case, however believe me view controller will be getting bigger and bigger in the real world scenario in a similar situation. So, let’s implement it with VIPER.</p><h4>Viper Module Implementation</h4><p>First thing first, we should create layers, like;</p><ul><li>AddressListView, aka <em>AddressListViewController</em></li><li>AddressListPresenter</li><li>AddressListInteractor</li><li>AddressListRouter</li><li>Address as <em>Entity</em></li></ul><p>Of course all these layers should move under the folder <em>AddressListModule</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*_4kGVK4cgBBzuOkMbm58Dw.png" /><figcaption>Initial AddressList Module Folder Structure</figcaption></figure><h4>Layer Interfaces</h4><p>To make responsibilities clearer, each layer should apply a protocol to open themselves to other layers, from now on I will call it <em>interface</em>. For example, what does presenter want AddressListView to do ? Most probably it gives an array of address properties which are listed in the screen. Also grouping protocol methods with a comment according to who will use them would be better.</p><p>Before jump to implementation directly, let’s define interfaces of layers;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47cea1282806953249f52e65dad4f27c/href">https://medium.com/media/47cea1282806953249f52e65dad4f27c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bbc89adae91fa9019bd2f94aca69a98/href">https://medium.com/media/4bbc89adae91fa9019bd2f94aca69a98/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7842594abd8909d64619ffa0f73ac04/href">https://medium.com/media/e7842594abd8909d64619ffa0f73ac04/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feceece0061f3ed6d7146783825ac50a/href">https://medium.com/media/feceece0061f3ed6d7146783825ac50a/href</a></iframe><p>How did we write all these ? Answer is simple, thinking about responsibilities of each layer. Just be sure that each layer applies it’s own interface after defining them 🙃</p><p>After interfaces are done, define associated layer variables in each layer considering which layer it should communicate with. You may want to look at the <strong><em>Figure 1</em></strong> at this moment.</p><p>Next we should think how we can create the module. Since different modules communicate between their <em>routers, </em>I think router should<em> </em>assemble the whole module. Since it is independent from module’s actual router instance, we can create a static module creation method in AddressListRouter;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/044c0b35670793e261500aafe1de9fd2/href">https://medium.com/media/044c0b35670793e261500aafe1de9fd2/href</a></iframe><p>Although static module creation method in router is just fine for me, I’d like to hear if you have a better idea.</p><p>Now, we can implement interface methods. Let’s check the <em>AddressListViewController</em> again after implementing methods;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83acf900063b346e2838a399b7040e2d/href">https://medium.com/media/83acf900063b346e2838a399b7040e2d/href</a></iframe><p>Now you can see that view has no idea what is going on. Each time a user touch event is happened, lifecycle method is called, view tells what happened to presenter instead of doing something itself. Even it does not contain any data related with addresses, it just asks to presenter what will be displayed in the cells while reloading table view. So let’s look at the presenter then;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/706ee9eef6f23894831b6d057a900ad8/href">https://medium.com/media/706ee9eef6f23894831b6d057a900ad8/href</a></iframe><p>As you can see that presenter determines what will happen next and invokes responsible layer. If fetching data is required, it tells to interactor, if the view should be updated, it makes it via view’s interface methods. Similarly, if a navigation stuff is required, it commands router to do it. However no UIKit related operation is allowed here. Also, when view is needed to address data, presenter gives only a part of the necessary properties will be displayed in the screen, it handled with giving <em>tuple</em> to view in the demo project.</p><p>Let’s look at the interactor;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0b2114a9c9d2ba0e4bd50172b19dc89/href">https://medium.com/media/f0b2114a9c9d2ba0e4bd50172b19dc89/href</a></iframe><p>Interactor is just responsible from service calls in this module. It fetches address list using it’s service property whenever presenter requested. Also if an error occurs, interactor notifies the presenter with associated error message. Although there is no analytics event sending or fetching local data in this module, interactor is responsible from them. At last, router implementation can be seen below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efac86fca7b4ea9b8eb9be333de079c1/href">https://medium.com/media/efac86fca7b4ea9b8eb9be333de079c1/href</a></iframe><p>Whenever you <em>present, pop or push </em>something, you should know that it is router’s job. As you can see above, router provides that navigate another view controller, as well as presenting something includes popups. Again, since it is a demo project there is only one module in it, router should communicate with other modules in a real project in terms of navigation.</p><h4>What about other stuff used in the module except layers ?</h4><p>We have used custom cell named <em>AddressListTableViewCell </em>in the view layer to present address data. Also <em>AddressListResponse</em> and <em>Address</em> models are used by interactor layer. Since these files are associated with AddressList module, we should move these files under the module’s folder in the project navigator;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*wjDFnv-FURPNVXwLTzy-xQ.png" /><figcaption>AddressList Module Folder Structure</figcaption></figure><h3>Final Words</h3><p>At the end of the story, we created an Viper module step by step. Although implementation of VIPER seems more work needed in first step, adding new capabilities to the layers is really easy thanks to the protocol oriented approach. Following data flow in the debugging is easy too, since each layer has a clear role. In addition to it, even view controller can be testable by using presenter when each life cycle method invoked and each user action happened.</p><p>However, it would be an overkill for the relatively small projects.</p><p>One last thing, if you are afraid number of layers that you should create for viper module, you may want to give a chance to script below, which is created by my teammate 😌</p><p><a href="https://github.com/cenksk/CIVIPERGenerator">CIVIPERGenerator</a></p><p>Happy coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd1f414b7dd3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trendyol-tech/creating-an-ios-viper-module-step-by-step-guide-cd1f414b7dd3">Creating an iOS Viper Module — Step by Step Guide</a> was originally published in <a href="https://medium.com/trendyol-tech">Trendyol Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Standalone Navigation Bar]]></title>
            <link>https://medium.com/trendyol-tech/standalone-navigation-bar-96ec32239dcf?source=rss-7c04f0bf8f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/96ec32239dcf</guid>
            <category><![CDATA[navigation-bar]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[standalone]]></category>
            <category><![CDATA[transitions]]></category>
            <dc:creator><![CDATA[Emre Ergün]]></dc:creator>
            <pubDate>Tue, 22 May 2018 23:44:05 GMT</pubDate>
            <atom:updated>2018-05-23T09:30:23.296Z</atom:updated>
            <content:encoded><![CDATA[<p>Declaring Navigation Bar’s Independence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*tjs8oj_ZuJ-6tWgOy7yz5Q.jpeg" /></figure><p>Most of the time, we use <strong><em>UINavigationBar</em></strong> just comes with <strong><em>UINavigationController</em></strong>. In this case, navigation controller creates our mighty bar, displays it and we can access the actual bar instance whenever we want by using navigation controller object. Also navigation controller set itself as delegate to associated navigation bar.</p><p>But how are all these navigational things managed? In fact, it has a quite logical mechanism. UINavigationBar contains an array of <em>UINavigationItem </em>for displaying content. According to Apple documents, UINavigationItem<em> </em>means;</p><blockquote>The items to be displayed by a navigation bar when the associated view controller is visible.</blockquote><p>For instance, whenever you pushed a view controller to a navigation controller stack, navigation controller gets navigation item of upcoming view controller and pushes this item into navigation bar’s navigation item array. Also if you pop current view controller from navigation stack, it’s navigation item will be popped from navigation bar’s navigation item array too. You should deal with navigation item of a view controller if you want to make changes on displayed navigation bar above it. The figure taken from Apple’s documentation can make clearer how this stuff works for you;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*j1fax2NstvdUxiovDjlb-Q.png" /><figcaption><a href="https://developer.apple.com/documentation/uikit/uinavigationbar">https://developer.apple.com/documentation/uikit/uinavigationbar</a></figcaption></figure><p>Of course all these stuff works automatically in the background most of the time, thanks to the navigation controller.</p><p>In fact, to clarify who has control over navigation bar mentioned above, if you ask who is navigation bar’s god, answer will definitely be <em>UINavigationController</em>.</p><p><strong><em>However</em></strong>, there may be some times we want to break this bond. You can think that it is not necessary, even you may think that it should be avoided since it is default behavior. But let’s take a look at simplify version of a problem I have faced in real world;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*xnuRBUEh2nbGpoZpociUtw.gif" /></figure><p>You can see that the navigation bar is fading while using interactive pop gesture. Actually I think it looks cool, however it may be an undesired behavior especially your product manager expect from you a solid transition from top of the screen to bottom. In this case, we should use standalone navigation bar.</p><h4>Standalone Navigation Bar</h4><p>Here is the bad news for navigation controller, we will use a totally new navigation bar created separately, instead of provided by navigation controller 😌</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F2UEMOWP7T1CzXhLWt9%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F2UEMOWP7T1CzXhLWt9%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F2UEMOWP7T1CzXhLWt9%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="243" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6e0a6cdc4b968e9938bcf4e9bb74d6a/href">https://medium.com/media/e6e0a6cdc4b968e9938bcf4e9bb74d6a/href</a></iframe><p>Before start, let’s take a look current code that updates navigation bar’s appearance in the second view controller which is pushed to stack;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53986b1ceff11c7217b7e90ff703655f/href">https://medium.com/media/53986b1ceff11c7217b7e90ff703655f/href</a></iframe><p>As you can see, we access navigation bar via navigation controller. Since we want a standalone bar, let’s hide navigation controller’s navigation bar using <strong><em>setNavigationBarHidden</em></strong><em> </em>in <em>viewWillAppear</em>.</p><p>So, we should create a navigation bar instance. However, as I mentioned above, navigation bar without at least one navigation item means basically nothing. Then let’s create a navigation item in a new method;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aead93c7daae81af4fc10465eaa02baf/href">https://medium.com/media/aead93c7daae81af4fc10465eaa02baf/href</a></iframe><p>Navigation item is ready to be displayed ✈️. We can create standalone navigation bar now;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b26372a9cdd2bded2c5826975e59a6f/href">https://medium.com/media/7b26372a9cdd2bded2c5826975e59a6f/href</a></iframe><p>To summarize what we did above, we have created a navigation bar instance first, then it is added to view controller’s view and constraints set. Finally, we have set our navigation item that contains start wars image as navigation item array to navigation bar. Let’s look at the result after putting all together and calling this method in <em>viewDidLoad;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*1ViwvrBmUyJwhaZR_BNPLg.jpeg" /></figure><p>Woops… It seems something is going wrong around to top of screen. Status bar isn’t interested in our new bar and it remained with same color. Remember that the delegate of the navigation bar associated with navigation controller is navigation controller itself. However our lonesome navigation bar’s delegate is not set yet. Let’s dig out <em>UINavigationControllerDelegate</em> in Apple’s documents addressed below;</p><p><a href="https://developer.apple.com/documentation/uikit/uinavigationbardelegate">UINavigationBarDelegate - UIKit | Apple Developer Documentation</a></p><p>You can see that it is mostly about giving callback information about <em>push</em> and <em>pop</em> on navigation item array. However if you look at the bottom of the page, you will notice that <strong><em>UINavigationBarDelegate</em></strong> inherits from other delegate called <strong><em>UIBarPositioningDelegate</em></strong>. I think it may help us about our little status bar problem 😌. Since owner of the standalone navigation bar is view controller currently presented, let’s set it as navigation bar’s delegate and implement <em>position </em>method as below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8202144be86f5795bf34089d8e3bd70d/href">https://medium.com/media/8202144be86f5795bf34089d8e3bd70d/href</a></iframe><p>After last changes, we can see it woks;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*xE_Njm5QTIhMz2iVHnnKbQ.jpeg" /></figure><p>There are still couple of problems exists. First, since we have hide navigation controller’s navigation bar in second view controller, swipe back gesture is disabled. To solve this, we will use a bit hack. Put the code below to second view controller’s <em>viewWillAppear</em> method and the problem solved.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56ef1956a5996dd6a6f95ed2c82b204a/href">https://medium.com/media/56ef1956a5996dd6a6f95ed2c82b204a/href</a></iframe><p>Second problem is there is no back button on the left of the navigation bar. We have to add this bar button ourselves. You can simply add a bar button with selector to the navigation item like below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb9f17963b7e663a7d7ce3caf5d186f1/href">https://medium.com/media/eb9f17963b7e663a7d7ce3caf5d186f1/href</a></iframe><p>Call this method with passing navigation item as parameter in where you initialized it. Then back button will work fine.</p><p>Thats all. As a result of the all stuff above, we have a relatively better swipe transition from top to bottom between these two view controllers;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*guU_qZVplf6uLYTZZTM_TQ.gif" /></figure><h4>Final Words</h4><p>At the end of the story, we have learned some basics of the <em>UINavigationBar</em> and implemented it as standalone object. Although all codes presented above enough for our little demo project, it would be wiser putting them in a class responsible from creation like <em>factory</em> or <em>builder</em> to initialize it easily when needed. Generally, I use standalone navigation bar in view controllers that contains custom transitions applied not only on view but also on navigation bar.</p><p>What do you think about using standalone navigation bar? Do you think that it is necessary to use in situations like above or similar behavior can be implementable with navigation bar associated with navigation controller ? Or do you prefer a customized <em>UIView</em> object instead of standalone navigation bar?</p><p>Have a nice day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96ec32239dcf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trendyol-tech/standalone-navigation-bar-96ec32239dcf">Standalone Navigation Bar</a> was originally published in <a href="https://medium.com/trendyol-tech">Trendyol Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Impression Event Helper]]></title>
            <link>https://medium.com/@ergunemr/ios-impression-event-helper-d194bcd6203a?source=rss-7c04f0bf8f17------2</link>
            <guid isPermaLink="false">https://medium.com/p/d194bcd6203a</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-analytics]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Emre Ergün]]></dc:creator>
            <pubDate>Tue, 10 Apr 2018 17:55:24 GMT</pubDate>
            <atom:updated>2018-04-10T18:04:27.716Z</atom:updated>
            <content:encoded><![CDATA[<p>A Mobile Analytics Event Story</p><h4>The Backstory</h4><p>Recently, one of my colleague who works for marketing department came around our team and said that he want to add just an another type of their exciting analytic events to our iOS app, named product listing impression. I have to confess that we love to implement marketing stuffs as whole team, who would not enjoy writing lots of junk code for just adding new analytic events in almost each sprint, instead of creating exciting new features for users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*x5cu3vduKSsFaq_ZwHD7Xw.jpeg" /></figure><p>So, first thing first, what does “impression” event mean ? Basically it means,</p><blockquote>An event that occurs when a user sees a content.</blockquote><p>Sending an event from app is an easy job (at least in most cases), but a small part of info from job’s description mentioned that there may be a challenge about this kind of event. When a user sees a content of cell completely, it count as impression and its okay to send it via event wrapper. But, if user sees less than half of a cell’s content, it should not counted as impression and no event should be sent in such case. In addition to this constraint, there is one more rule to be aware of. In terms of clarity, lets define our rules as follows,</p><ol><li>User should see more than half of a cell to count this event as impression</li><li>Events which are already sent should not send again, ever if user sees these cells again.</li></ol><p>Unfortunately there is no method or callback are provided from UICollectionView to use directly in such cases. Therefore, let’s write an impression event handler to detect which cells are seen by users, as enough as to count as impression. ✌️</p><h4>Coding Part</h4><p>First thing first, lets create our handler class, I named it <em>ListingImpressionStalker </em>(and yes, actually this naming defines what it really does), and define two variables with a basic initializer and a public method;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7da1c455870494397a06f01e08538ed5/href">https://medium.com/media/7da1c455870494397a06f01e08538ed5/href</a></iframe><p><em>minimumPercentageOfCell</em> is our ratio constraint related with the minimum percentage of seen part of the cell viewed by user to count as impression, <em>collectionView</em> is just a weak collectionView reference which is tracked for events.</p><p>Lets start to write some code for the <em>stalkCells()</em> method. First we need cells which are currently visible to user. Lucy for us, UICollectionView has a method named <em>visibleCells() </em>which returns visible cell instances currently visible. We should get these cells by calling this method, then percentage of viewed area calculation should be made for each cell by iterating them. So lets put these into code,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc207474e56e6521e1ca95c61a225e15/href">https://medium.com/media/bc207474e56e6521e1ca95c61a225e15/href</a></iframe><p>Steps followed in this method are really simple,</p><ol><li>Use guard statement to create local variables indexPath and layoutAttributes safely for cell.</li><li>Find cell’s true position in the superview.</li><li>Calculate intersection rect using collectionView’s frame and cell’s frame in superview which is calculated one line above.</li><li>Calculate percentage of intersection and return it.</li></ol><p>Thats it. Since we know percentage of the viewed area of the related cell, we can decide whether this view should be count as impression event or not, depends on the return value of this method. Lets create a protocol to send index paths we found using <em>delegate</em> pattern.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea03abc775155e77b00016e5cac9d87d/href">https://medium.com/media/ea03abc775155e77b00016e5cac9d87d/href</a></iframe><p>Using <em>sendEventForCell(atIndexPath indexPath:Indexpath) </em>method of this protocol<em>, </em>we can send index paths to class which is conforming <em>ListingImpressionStalkerDelegate.</em></p><p>We have iterated visible cells and view percentage calculation has done for each cell. In terms of requirements, there is one last thing left, lets remember our second rule,</p><blockquote>Already sent events should not send again ever if user sees these cells again.</blockquote><p>To achieve this, we can easily create an array to store already sent index paths. Is it enough ? Maybe for the most time, yes it is; however we should make it as flexible as possible to cover many cases. To leave this choice to the user, lets create a protocol named <em>ListingImpressionItem.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3808e2d8dadaf422b871d7d0792c8f90/href">https://medium.com/media/3808e2d8dadaf422b871d7d0792c8f90/href</a></iframe><p>Cells which are belong to the collection view we tracked should conform this protocol to provide unique identifier. Now we can store these unique ids instead of index paths to prevent sending new event again. After defining <em>ListingImpressionStalkerDelegate </em>and<em> ListingImpressionItem </em>protocols<em>, </em>we can complete our <em>stalkCells() </em>method as follows,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a15d1d1e95397a3fae5afe9dae5d312/href">https://medium.com/media/3a15d1d1e95397a3fae5afe9dae5d312/href</a></iframe><h4>Final Words</h4><p>In the end of the story, we have completed our simple impression event handler. After conforming protocols mentioned above and implementing their methods, calling <em>stalkCells()</em> in viewDidAppear()<em> </em>and<em> </em>scrollViewDidScroll() methods would be enough. Thanks to the <em>ListingImpressionStalkerDelegate, sendEventForCell() </em>method is invoked automatically with index paths of cells which are seen more than half of their content, like following code snippet,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4a6f0134b5e336b67a15d98d280babc/href">https://medium.com/media/c4a6f0134b5e336b67a15d98d280babc/href</a></iframe><p>For those who do not want to make dirty their hands, completed code is in the following link,</p><p><a href="https://github.com/ergunemr/ListingImpressionStalker">ergunemr/ListingImpressionStalker</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d194bcd6203a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>