<?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 Quinton Pryce on Medium]]></title>
        <description><![CDATA[Stories by Quinton Pryce on Medium]]></description>
        <link>https://medium.com/@quinton138?source=rss-4d22389a8225------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*tqhGHgBGn4sz5iEWsVkRIg.jpeg</url>
            <title>Stories by Quinton Pryce on Medium</title>
            <link>https://medium.com/@quinton138?source=rss-4d22389a8225------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:17:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@quinton138/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[A Slimmer Approach To Moya]]></title>
            <link>https://medium.com/1v1me-blog/a-slimmer-approach-to-moya-3de6a62f9bdb?source=rss-4d22389a8225------2</link>
            <guid isPermaLink="false">https://medium.com/p/3de6a62f9bdb</guid>
            <category><![CDATA[boilerplate]]></category>
            <category><![CDATA[moya]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Quinton Pryce]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 19:30:59 GMT</pubDate>
            <atom:updated>2023-08-25T22:29:06.169Z</atom:updated>
            <content:encoded><![CDATA[<p>We have been using Moya since our inception. However simple their framework, their recommendation for API definition creates many many lines of boilerplate, and has me feeling like oh-no-this-can’t-be-good, after forgetting I’ve got food in the oven.</p><p>But mark it on the calendar, because today we will no longer create boilerplate and no longer forget we are cooking (…yes we will, who are we kidding).</p><h3>Moya</h3><p>Have a look at the example below. For a simple <strong>get</strong> request, we just wrote the request name 5 times (a big no no, if you can help it).</p><p>Having boilerplate isn’t always the worst, but if feels real bad when this enum starts to grow and you have to scroll through hundreds of lines to add a single request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/416892951c229c6eb972714fc089a3cd/href">https://medium.com/media/416892951c229c6eb972714fc089a3cd/href</a></iframe><p>I hope if you’ve written something similar to this you’re now saying “why have I dealt with this for so long”.</p><h3>Our New Approach</h3><p>You can see with the example below how SLEEK this got. Every request can be fully digested in one line, new items can be added with as little as 3 lines as compared to 9 lines in Moya’s recommended solution, and we get to use this nice dot notation that we are all loving in SwiftUI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b04ac244ec7292ba97f1f3b2390dd541/href">https://medium.com/media/b04ac244ec7292ba97f1f3b2390dd541/href</a></iframe><h3>My Blogs-Need-Conclusions Conclusion</h3><p>I don’t really want to tell you how many lines this saved me but it does rhyme with burmalurgadura<strong>thousand</strong>. I’ve got a can’t stop-won’t stop attitude toward removing boilerplate, especially when it starts to form an enum that is too large to view on my teeny-tiny Macbook screen.</p><p>*Bows Deeply*</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3de6a62f9bdb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/1v1me-blog/a-slimmer-approach-to-moya-3de6a62f9bdb">A Slimmer Approach To Moya</a> was originally published in <a href="https://medium.com/1v1me-blog">1v1Me Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Live Activities in iOS with FCM & APNS]]></title>
            <link>https://medium.com/1v1me-blog/live-activities-in-ios-with-fcm-apns-f2aace55c616?source=rss-4d22389a8225------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2aace55c616</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[live-activities]]></category>
            <category><![CDATA[dynamic-island]]></category>
            <dc:creator><![CDATA[Quinton Pryce]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 16:04:29 GMT</pubDate>
            <atom:updated>2023-07-04T16:04:29.151Z</atom:updated>
            <content:encoded><![CDATA[<p>If you came here because you wanted to use FCM to update your live activity, I’m sorry. At the time of this article, FCM does not currently support custom payloads. However! 1v1Me uses FCM &amp; we spent less than a day writing the code to use APS directly AND YOU CAN TOO! 🥳</p><p>We had a few challenges with this project:</p><ul><li>The Apple docs are incomplete (<a href="https://feedbackassistant.apple.com/feedback/12336302">and have the wrong keys</a>)</li><li>The payload is finicky &amp; difficult to debug decoding errors</li><li>Using network images is undocumented &amp; not obvious</li></ul><p>This blog isn’t going to provide detailed, step-by-step guidance. Rather, it will highlight some of the difficulties we encountered. So I highly recommend familiarizing yourself with the Apple docs first.</p><h3>Getting Your APNS Token</h3><p>When a new activity is created, a new push token is generated and we subscribe to the corresponding live activity via our subscribeToLiveActivity method.</p><pre>@available(iOS 16.2, *)<br>private func start(attributes: EventActivityAttributes, state: EventActivityAttributes.EventState) {<br>    do {<br>        //…<br>        <br>        let activity = try Activity&lt;EventActivityAttributes&gt;.request(<br>            attributes: attributes,<br>            content: content,<br>            pushType: .token<br>        )<br>        <br>        Log.d(&quot;Requested an Event Activity \(activity.id)&quot;)<br>        Task {<br>            for await data in activity.pushTokenUpdates {<br>                let token = data.map { String(format: &quot;%02x&quot;, $0) }.joined()<br>                <br>                Service.stake.subscribeToLiveActivity(eventId: attributes.eventId, token: token, completion: { _ in })<br>            }<br>        }<br>        <br>    } catch {<br>        Log.d(&quot;Error requesting Event Activity \(error.localizedDescription) \(error)&quot;)<br>    }<br>}</pre><p>This method collects token updates asynchronously, with each update containing raw bytes that we convert to a string representation of the hexadecimal value. The resulting string (the token) is then used to subscribe to the live activity with our backend, which will be making use of push notifications to update our live activity.</p><h3>Decoding/Encoding</h3><p>Let’s shift our focus to the ContentState struct. The widget uses this (and the ActivityAttributes) to receive and decode data from your app &amp; your server. The Coding aspect of our live activity caused us a few headaches to say the least (it took longer to dubug this then anything else in the project…).</p><h4>Debugging Issues</h4><p>Debugging the widget can be difficult. I highly recommend writing a custom initializer for your content state and printing any of your debugging errors with the error information to the console. Apple does let you know there is an error in your console, but it won’t give you the specifics needed to debug the issue (ex. which key is the offending member in decoding errors).</p><pre>init(from decoder: Decoder) throws {<br>        do {<br>            //...<br>        } catch let DecodingError.dataCorrupted(context) {<br>            print(context)<br>            throw DecodingError.dataCorrupted(context)<br>        } catch let DecodingError.keyNotFound(key, context) {<br>            print(&quot;Key &#39;\(key)&#39; not found:&quot;, context.debugDescription)<br>            print(&quot;codingPath:&quot;, context.codingPath)<br>            throw DecodingError.keyNotFound(key, context)<br>        } catch let DecodingError.valueNotFound(value, context) {<br>            print(&quot;Value &#39;\(value)&#39; not found:&quot;, context.debugDescription)<br>            print(&quot;codingPath:&quot;, context.codingPath)<br>            throw DecodingError.valueNotFound(value, context)<br>        } catch let DecodingError.typeMismatch(type, context) {<br>            print(&quot;Type &#39;\(type)&#39; mismatch:&quot;, context.debugDescription)<br>            print(&quot;codingPath:&quot;, context.codingPath)<br>            throw DecodingError.typeMismatch(type, context)<br>        } catch {<br>            print(&quot;error: &quot;, error)<br>            throw error<br>        }<br>    }</pre><h4>Custom Decoding &amp; Dates</h4><p>When your app initializes the struct, it will use Apple’s default encoding strategies. So if you decode an object that is shared between the two targets with a date (for example) and want to encode that date, your widget will not be able to decode it. I tried many many ways around this (widget target only custom decoders, app only targeted encoders), but nothing worked. The only way around this was to define a new “Widget Safe Struct” (ie. not containing any custom types) and using it to send data to your widget.</p><p>When you receive any dates in your ContentState, they either need to match the default date format Apple has provided or you can use a TimeInterval/ Double and convert in inside the widget to a Date if you need it.</p><pre>struct ContentState: Codable, Hashable {<br>    //…<br>    <br>    init(from decoder: Decoder) throws {<br>        do {<br>            let container = try decoder.container(keyedBy: CodingKeys.self)<br>            <br>            let epochStartDate = try container.decode(Double.self, forKey: .startDate)<br>            startDate = Date(timeIntervalSince1970: epochStartDate)<br>            <br>            //…<br>        } catch {<br>            throw error<br>        }<br>    }<br>    <br>    //…<br>}</pre><p><em>We use the Date object heavily in the live activity, so we decode the Double into a date object.</em></p><h4>Passing Large Content States (Images)</h4><p>The content state is limited to 4mb, which means you can’t encode image data. We’ll talk about how to fix this in the next section.</p><h3>Using URL/Network Images</h3><p>We use a lot of network images at 1v1Me, and it was a requirement for us to be able to send them.</p><p>Nowhere in the docs does it mention how to use network images, but it was asked in a live coding session in a WWDC session &amp; the answer they gave was that the best solution is to use App Groups &amp; UserDefaults. The following is a simple implementation of that:</p><h4>Our Live Activities Network Image View</h4><pre>struct NetworkImage: View {<br>    let url: URL?<br>    var renderingMode: Image.TemplateRenderingMode = .original<br>    var placeholder: Image?<br>    <br>    var body: some View {<br>        Group {<br>            if let url = url, let imageData = UserDefaults.appGroupsDefaults?.data(forKey: url.absoluteString),<br>               let uiImage = UIImage(data: imageData)?.resized(toWidth: 300)?.withRenderingMode(renderingMode == .original ? .alwaysOriginal : .alwaysTemplate) {<br>                Image(uiImage: uiImage)<br>                 .resizable()<br>                <br>            } else if let placeholder {<br>                placeholder.foregroundColor(.theme.gray3)<br>            } else {<br>                Spacer()<br>            }<br>        }<br>    }<br>}<br><br>// Many of our imagery tends to be larger than the<br>// max size Apple has in place (1400x500px)<br>extension UIImage {<br>    func resized(toWidth width: CGFloat, isOpaque: Bool = false) -&gt; UIImage? {<br>        let canvas = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))<br>        let format = imageRendererFormat<br>        format.opaque = isOpaque<br>        return UIGraphicsImageRenderer(size: canvas, format: format).image { _ in<br>            draw(in: CGRect(origin: .zero, size: canvas))<br>        }<br>    }<br>}<br><br>extension UserDefaults {<br>    static var appGroupsDefaults: UserDefaults? = UserDefaults(suiteName: &quot;group.com.widgets.images&quot;)<br>}</pre><h4>Our Upload Technique For Network Images</h4><p>We use KingFisher in our main app, but you can use whatever method you use to download images (ie. URLSession).</p><pre>func downloadAndStoreInAppGroup(url: URL?) async {<br>    guard let url else { return }<br>    await withCheckedContinuation { continuation in<br>        KingfisherManager.shared.retrieveImage(with: url, options: nil, progressBlock: nil, completionHandler: { result in<br>            // Log.t(&quot;Downloaded image from Kingfisher for Widget \(result)&quot;)<br>            switch result {<br>            case .success(let imageResult):<br>                guard let data = imageResult.data() else { return }<br>                Current.appGroupDefaults?.set(data, forKey: url.absoluteString)<br>                <br>            case .failure:<br>                break<br>            }<br>            <br>            continuation.resume()<br>        })<br>    }<br>}</pre><h3>Server Side Formatting</h3><p>We are using CURB for our HTTP Library which you’ll need to add or use something similar. Ensure that you have added your appropriate Service Key which can be generated on the Apple Developer Portal.</p><p>Nothing special about this implementation other than the formatting that we’ve included below &amp; the push URLs that you’ll need for sandbox (Debug iOS builds) and production (Release iOS builds).</p><pre>SANDBOX_PUSH_URL = &#39;https://api sandbox push apple com:443/3/device/%s&#39; freeze<br>PRODUCTION_PUSH_URL = &#39;https://api push apple com:443/3/device/%s&#39; freeze<br><br>ACTIVITY_EVENT_TYPES = {<br>  update: &#39;update&#39;,<br>  end: &#39;end&#39;<br>  } freeze<br><br>def self live_activity(device_token, event, relevancy_score, dismissal_date, content_state = {}, alert = {})<br>  ec_key = OpenSSL::PKey::EC new(AppleKeys push_key_private)<br>  jwt_token = JWT encode({ iss: ENV[&#39;APPLE_TEAM_ID&#39;], iat: Time now to_i }, ec_key, &#39;ES256&#39;, { kid: ENV[&#39;APNS_KEY_ID&#39;] })<br><br>  payload = {<br>  aps: {<br>  alert: alert,<br>  timestamp: Time now to_i,<br>  event: event,<br>  &#39;relevance-score&#39; =&gt; relevancy_score,<br>  &#39;content-state&#39; =&gt; content_state<br>  }<br>  }<br><br>  payload[:aps][&#39;dismissal-date&#39;] = dismissal_date unless dismissal_date nil?<br><br>  http = Curl::Easy http_post(format(ENV[&#39;PUSH_URL&#39;], device_token), payload to_json) do |curl|<br>  curl headers[&#39;Content-Type&#39;] = &#39;application/json&#39;<br>  curl headers[&#39;Accept&#39;] = &#39;application/json&#39;<br>  curl headers[&#39;apns-topic&#39;] = &quot;#{ENV[&#39;BUNDLE_ID&#39;]} push-type liveactivity&quot;<br>  curl headers[&#39;apns-priority&#39;] = &#39;10&#39;<br>  curl headers[&#39;apns-push-type&#39;] = &#39;liveactivity&#39;<br>  curl headers[&#39;Authorization&#39;] = &quot;Bearer #{jwt_token}&quot;<br>  end<br><br>  raise &quot;Error sending live activity push notification: #{http body}&quot; unless http response_code &lt;= 299<br><br>  true<br>  end</pre><h3>Conclusion</h3><p>In conclusion, implementing Live Activities can significantly enrich the user experience of your app by extending it to the Lock Screen &amp; Dynamic Island. However, this feature comes with its unique set of challenges. Throughout this post, we have delved into these challenges, sharing our experiences and solutions we’ve discovered along the way. From addressing incomplete Apple documentation to dealing with issues related to encoding/decoding and server-side formatting.</p><p>Our hope is that this blog post will act as a valuable guide to illuminate some of these technical intricacies and make the process of adding a Live Activity to your app a much smoother one. As with any technical implementation, continual learning and adjustment are essential, so keep exploring and innovating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2aace55c616" width="1" height="1" alt=""><hr><p><a href="https://medium.com/1v1me-blog/live-activities-in-ios-with-fcm-apns-f2aace55c616">Live Activities in iOS with FCM &amp; APNS</a> was originally published in <a href="https://medium.com/1v1me-blog">1v1Me Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Bottom Sheet in SwiftUI with a Scrolling Option]]></title>
            <link>https://medium.com/1v1me-blog/building-a-bottom-sheet-in-swiftui-with-a-scrolling-option-201bf24bb216?source=rss-4d22389a8225------2</link>
            <guid isPermaLink="false">https://medium.com/p/201bf24bb216</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[bottomsheet]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Quinton Pryce]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 20:05:44 GMT</pubDate>
            <atom:updated>2023-06-01T20:05:44.170Z</atom:updated>
            <content:encoded><![CDATA[<p>As the modern user interface leans towards more gesture-based navigation, it&#39;s common to encounter the &quot;bottom sheet&quot; interface — a card that slides up from the bottom covering part of the screen. In this post, we&#39;ll look at creating a customizable bottom sheet in SwiftUI, and we will even add the ability to handle large content by making it scrollable.</p><h3>Creating a Basic Bottom Sheet</h3><p>First, we start by creating the BottomSheet struct. This struct is a SwiftUI View that takes a title, a BottomSheetCloser and a closure for the content of the sheet. The BottomSheetCloser is an ObservableObject that provides a simple interface to open and close the sheet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dafc231011ba54c757b3ba372c92559/href">https://medium.com/media/9dafc231011ba54c757b3ba372c92559/href</a></iframe><p>The bottom sheet is presented as a ZStack with a semi-transparent black background and the sheet itself. The sheet uses a GeometryReader to adjust the offset for the slide-up animation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1da6ecfc9537066cdca2e453697073d2/href">https://medium.com/media/1da6ecfc9537066cdca2e453697073d2/href</a></iframe><h3>Adding Scrolling Capability</h3><p>For larger contents, the bottom sheet may end up taking too much of the screen real estate. This is where the ScrollingBottomSheet comes in. This struct is a wrapper around the BottomSheet that makes the content scrollable when it exceeds a certain height. The decision to use either a plain content or a ScrollView is done dynamically based on the calculated content height.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2a2ac4f94bc57ce0c55794a69acb6df/href">https://medium.com/media/a2a2ac4f94bc57ce0c55794a69acb6df/href</a></iframe><p>The content height is calculated using a GeometryReader overlay on the content. This overlay doesn&#39;t affect the content&#39;s appearance or interaction but allows us to read its size.</p><h3>The Future: Swipe to Dismiss &amp; Improvements</h3><p>There&#39;s always room for improvement and expansion. One potential enhancement could be the ability to swipe down the sheet to dismiss it.</p><p>In the time I spent looking at this code, I only now realize there are some things in here that not all bottom sheets have (title, backgrounds, close buttons). These could be generalized away, but for 1v1Me it makes it easy to spin up a consistent header &amp; background for the sheets without having to constantly use “ThemedBottomSheet.swift” all the time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=201bf24bb216" width="1" height="1" alt=""><hr><p><a href="https://medium.com/1v1me-blog/building-a-bottom-sheet-in-swiftui-with-a-scrolling-option-201bf24bb216">Building a Bottom Sheet in SwiftUI with a Scrolling Option</a> was originally published in <a href="https://medium.com/1v1me-blog">1v1Me Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing SwiftUI Buttons With ButtonStyle]]></title>
            <link>https://medium.com/1v1me-blog/customizing-swiftui-buttons-with-buttonstyle-9b32e7f41c97?source=rss-4d22389a8225------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b32e7f41c97</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[haptics]]></category>
            <dc:creator><![CDATA[Quinton Pryce]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 23:18:58 GMT</pubDate>
            <atom:updated>2022-12-19T23:18:58.584Z</atom:updated>
            <content:encoded><![CDATA[<p>SwiftUI’s <strong>ButtonStyle</strong> can be a really powerful configuration tool to make quick &amp; concise buttons for your app.</p><p><strong>ButtonStyles </strong>let us define a set of modifiers to apply to a button in one line <em>(theming, animations, </em><strong><em>haptics</em></strong><em>, etc.)</em>.</p><h4>Theming With ButtonStyles</h4><p>One of the <strong>ButtonStyles</strong> at 1v1Me is a <strong>Pill</strong>. We have written custom initializers for frequently used <strong>backgroundColor</strong> and <strong>titleColor</strong> combinations.</p><pre>struct Pill: ButtonStyle {<br>    let backgroundColor: Color<br>    let titleColor: Color<br>    <br>    static var destructive: Pill {<br>        return Pill(backgroundColor: .red, titleColor: .white)<br>    }<br><br>    func makeBody(configuration: Configuration) -&gt; some View {<br>        configuration.label<br>            .font(.system(size: 16, weight: .bold))<br>            .padding(.horizontal, 16)<br>            .background(backgroundColor)<br>            .foregroundColor(titleColor)<br>            .frame(maxWidth: .infinity)<br>            .frame(height: 48)<br>            .clipShape(Capsule())<br>    }<br>}<br><br>Button(&quot;Press Me!&quot;, action: {<br>    print(&quot;Hello, World!&quot;)<br>})<br>.buttonStyle(Pill.destructive)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*m5usvOkfVbTedw7M7KMJwg.png" /></figure><h4>Ensure Tapability</h4><p>Not all buttons are going to have content from edge-to-edge. Our event card is a custom view inside a button with some empty areas which are not tappable by default:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*Bm3pb7qwgGSOloHPZ0rJ6w.jpeg" /><figcaption>Buttons are not tappable by default if the views do not extend all the way to the sides. Any area that is black in our event card is not tappable without additional customization.</figcaption></figure><p>To fix this we can add a content shape to our <strong>ButtonStyle</strong> to ensure that the entire button is tappable.</p><pre>struct Tappable: ButtonStyle {<br>    func makeBody(configuration: Configuration) -&gt; some View {<br>        configuration.label<br>            .contentShape(Rectangle())<br>    }<br>}</pre><h4>Adding Touch Animations &amp; Haptics To Buttons</h4><p>If you want to add more familiarity to your buttons &amp; bring a sense of touch you can add <strong>animations.</strong></p><pre>struct ScaleOnTap: ButtonStyle {<br>    func makeBody(configuration: Configuration) -&gt; some View {<br>        configuration.label<br>            .scaleEffect(configuration.isPressed ? 0.95 : 1)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*r2J-wEGNQ8ZEaw2x3JjjCA.gif" /></figure><h4>Adding Haptics To Buttons</h4><p><strong>Haptics</strong> are a powerful way to bring your app into the physical world.</p><p>The simplest way to add <strong>Haptics</strong> to your buttons within your <strong>ButtonStyle </strong>is to lean on the animations that you might have already set.</p><pre>struct ScaleOnTap: ButtonStyle {<br>    func makeBody(configuration: Configuration) -&gt; some View {<br>        configuration.label<br>            .scaleEffect(<br>                configuration.isPressed ? <br>                    { Global.haptics.interaction(); return 0.95 }() : 1<br>            )<br>    }<br>}</pre><p>Unfortunately, SwiftUI hasn’t made any hooks available for button taps in <strong>ButtonStyles </strong>besides <strong>simultaneousGesture </strong>which unfortunately doesn’t work when applied to the label of the <strong>Button</strong>.</p><p>Other than this shoehorn we added to get haptics in our <strong>ButtonStyles</strong>, you can go with a custom button with tap gestures to get the same result.</p><h4>Bonus Haptics Interaction Example</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03a69d9ee2c00b2e2f29f8251f8e9af8/href">https://medium.com/media/03a69d9ee2c00b2e2f29f8251f8e9af8/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b32e7f41c97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/1v1me-blog/customizing-swiftui-buttons-with-buttonstyle-9b32e7f41c97">Customizing SwiftUI Buttons With ButtonStyle</a> was originally published in <a href="https://medium.com/1v1me-blog">1v1Me Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building 1v1Me’s Video Feed On iOS]]></title>
            <link>https://medium.com/1v1me-blog/building-1vmes-video-feed-on-ios-74706cfa739?source=rss-4d22389a8225------2</link>
            <guid isPermaLink="false">https://medium.com/p/74706cfa739</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Quinton Pryce]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 03:53:31 GMT</pubDate>
            <atom:updated>2022-07-08T04:07:15.854Z</atom:updated>
            <content:encoded><![CDATA[<p>Every major social media app is doing it.</p><ul><li>TikTok’s Feed</li><li>Instagram’s Reels</li><li>Facebook’s Videos</li><li>YouTube’s Shorts</li></ul><p>This full-screen page style is everywhere, but Apple has not made implementing it very easy.</p><figure><img alt="1v1Me Clips uses this UI pattern to show videos in landscape &amp; portrait mode." src="https://cdn-images-1.medium.com/max/320/1*qaal_oIsN6uOxsDXGBJsuQ.gif" /><figcaption>1v1Me Clips uses this UI pattern to show videos in landscape &amp; portrait mode.</figcaption></figure><p>This guide will walk you through how to build this full-screen TikTok-style UI pattern into your app for both landscape and portrait mode. You can view the <a href="https://github.com/1v1Me/FullScreenCollectionViewController/tree/main">full example here</a>.</p><h3>The Layout</h3><p>1. Set cell spacing to 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60ba4b7494fbc6b4ccacaec3e1660109/href">https://medium.com/media/60ba4b7494fbc6b4ccacaec3e1660109/href</a></iframe><p>2. Set the preRotationFirstIndexPath.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42a21267df4e7b0ef9207b1a71d5282e/href">https://medium.com/media/42a21267df4e7b0ef9207b1a71d5282e/href</a></iframe><p>3. Set the target content offset point during rotation. This prevents other cells from showing while the phone is rotating.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa16ec0ebee7110f884d7c0929bab43b/href">https://medium.com/media/aa16ec0ebee7110f884d7c0929bab43b/href</a></iframe><p>4. After the rotation, double-check that the cell we landed on is the cell that was shown before the rotation started.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07513ce0f4e121f9499d4962e989387d/href">https://medium.com/media/07513ce0f4e121f9499d4962e989387d/href</a></iframe><p>5. After letting go of a scroll gesture we need to calculate what offset point (collection view cell) to snap to using the proposedContentOffset and the velocity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/750e65d6132b2334256a2e58def1efd0/href">https://medium.com/media/750e65d6132b2334256a2e58def1efd0/href</a></iframe><p><a href="https://github.com/1v1Me/FullScreenCollectionViewController/blob/main/FullScreenSwiping/FullPageCollectionViewFlowLayout.swift">Putting it all together</a> gives us a flow layout that powers a full-screen swipeable collection view. A complex but robust solution.</p><h3>The View Controller</h3><p>The base view controller is very simple.</p><p>It is responsible for setting up the collection view:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c30d4f85b3b2d931ff0a330248b82296/href">https://medium.com/media/c30d4f85b3b2d931ff0a330248b82296/href</a></iframe><p>&amp; for setting the layout’s indexPathForCellInFrameBeforeBoundsChange:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17e6d86283571809a348169c49739d09/href">https://medium.com/media/17e6d86283571809a348169c49739d09/href</a></iframe><p>There we have it. A layout that handles which cell to show after a swipe gesture &amp; after a phone rotation, and a simple view controller to house it.</p><p>Extending the view controller we described here is easy as shown in the <a href="https://github.com/1v1Me/FullScreenCollectionViewController">full example</a> to allow you to use this UI pattern across your different views.</p><h3>Props To Innovation, But Could You Share It?</h3><p>Apple has done an impressive job laying out foundational UI patterns for iOS Developers to easily implement. Even with <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjQrMim1-f4AhW1GzQIHaPrCzsQFnoECA0QAw&amp;url=https%3A%2F%2Fwww.apple.com%2Fca%2Fapp-store%2F&amp;usg=AOvVaw314p_wHzTPXBBnIXe5CENX">nearly two million apps</a> on the App Store, there are a leading few who pave new, non-native roads through the landscape. And although ingenuity &amp; creativity should be praised, it makes app-building more difficult for small teams due to the user’s custom-UI expectations from the top few apps.</p><p>My Grandma wrote me a note with three pieces of advice. One of them was <strong>“Get involved in your community”</strong>. No matter who you are, what you do, or what level you are, you’re experience is vital to your communities heartbeat and continued growth.</p><p>If you solve an interesting problem, try to share it. Any bit helps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqCbrwcLQp3itxGX-0_9yg.jpeg" /><figcaption>This is the note she gave me many years ago. Embrace Optimism, Get involved in your community, Enjoy this moment.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74706cfa739" width="1" height="1" alt=""><hr><p><a href="https://medium.com/1v1me-blog/building-1vmes-video-feed-on-ios-74706cfa739">Building 1v1Me’s Video Feed On iOS</a> was originally published in <a href="https://medium.com/1v1me-blog">1v1Me Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Xcode Cloud With Firebase]]></title>
            <link>https://medium.com/1v1me-blog/using-xcode-cloud-with-firebase-3bc66e7094bb?source=rss-4d22389a8225------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bc66e7094bb</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[xcode-cloud]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Quinton Pryce]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 23:11:05 GMT</pubDate>
            <atom:updated>2022-06-15T01:34:51.898Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you know what’s the worst? A long intro.</p><h3>Xcode Cloud Initial Setup</h3><p>Apple did a lovely job of <a href="https://developer.apple.com/documentation/xcode/configuring-your-first-xcode-cloud-workflow">documenting the initial setup here</a>.</p><p><em>I won’t dive into any setup details, but if you struggle at all with weird errors popping up, first ensure your Xcode &amp; Mac OS are on the newest versions.</em></p><h3>Customizing Workflows</h3><p>Hats off to the iOS Dev Ops out there, but I couldn’t be happier to delete fastlane &amp; move to <em>the cloud</em>.</p><h4>My setup</h4><p>I now have two Workflows:</p><ol><li>a<strong> debug</strong> build using <strong>Firebase’s App Distribution</strong>.</li><li>a <strong>release</strong> build using <strong>TestFlight</strong>.</li></ol><h4>My additional needs</h4><ol><li>Upload a build to Firebase.</li><li>Upload dsyms to Firebase’s Crashlytics.</li><li>Tag the build version on git.</li></ol><p><em>Adding these additional features requires </em><a href="https://developer.apple.com/documentation/xcode/writing-custom-build-scripts"><em>writing custom build scripts</em></a><em>.</em></p><h4>Uploading a build to Firebase</h4><ol><li><a href="https://firebase.google.com/docs/cli#install_the_firebase_cli">Download the Firebase CLI script</a> &amp; zip it inside your <em>ci_scripts </em>folder. <br><em>Read over the </em><a href="https://firebase.google.com/docs/app-distribution/ios/distribute-cli"><em>Firebase CLI Script doc</em></a><em> if you’re unsure how to use it.</em></li><li>Execute the upload in ci_post_xcodebuild.sh.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cd84e9ad45d3f21407bc1de30abc447/href">https://medium.com/media/6cd84e9ad45d3f21407bc1de30abc447/href</a></iframe><h4>Uploading dsyms to Firebase</h4><ol><li>Find and copy your <a href="https://firebase.google.com/docs/crashlytics/get-deobfuscated-reports?platform=ios">upload-symbols</a> script in your Crashlytics framework.</li><li>Execute the upload in ci_post_xcodebuild.sh.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e233b8e399e196d533c031f6e437c191/href">https://medium.com/media/e233b8e399e196d533c031f6e437c191/href</a></iframe><h4>Create a git tag of the distributed version</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da82b0d6abdc7537511ef4b47b27e8f8/href">https://medium.com/media/da82b0d6abdc7537511ef4b47b27e8f8/href</a></iframe><p>Mic. Drop.</p><p><em>Often I tend around the bush, rather than beating straight through it. I have taken my personal Dev Ops nightmare, of learning how to customize Xcode Cloud as an opportunity to tersely document the intricacies of a Firebase configuration.</em></p><p><em>If in this article you missed the personal story, inside jokes, gifs, &amp; LinkedIn plug, I’d invite you to look at any of Medium’s other blogs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bc66e7094bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/1v1me-blog/using-xcode-cloud-with-firebase-3bc66e7094bb">Using Xcode Cloud With Firebase</a> was originally published in <a href="https://medium.com/1v1me-blog">1v1Me Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing UIView frames]]></title>
            <link>https://medium.com/textnowengineering/unit-testing-uiview-frames-51f134bdd0a6?source=rss-4d22389a8225------2</link>
            <guid isPermaLink="false">https://medium.com/p/51f134bdd0a6</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[uiview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[textnow]]></category>
            <dc:creator><![CDATA[Quinton Pryce]]></dc:creator>
            <pubDate>Fri, 09 Oct 2020 15:39:19 GMT</pubDate>
            <atom:updated>2020-10-09T15:39:19.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*i3ICHFeYv8rpwRuq_hSxbg.png" /><figcaption>Note that test tubes are not included with XCUITests</figcaption></figure><p>Here’s a thing that all iOS developers know, but (usually) don’t say out loud: Testing your views on all of the possible iOS screen sizes is exhausting. XCUITests are dreadfully slow, and screenshot tools are painful to update and error prone.</p><p>So we’re left with one option: Unit testing our views.</p><h4>What you’ll need.</h4><ul><li><strong>A programmatic view controller. </strong><br>If your view controller is not programmatic you won’t be able to instantiate it with a particular frame. Loading your view controller from a storyboard or XIB will limit you to the simulator you are running that test on.</li><li><strong>A good attitude.</strong></li></ul><h4>What’s our end game?</h4><p>We want to be at a place where making small view changes doesn’t give us a stomach ache. And, arguably more importantly, we want to be able to easily and quickly test our views on all screen sizes.</p><h4>1. Create your helpers.</h4><h4>a)<strong> View controller factory.</strong></h4><p>You will likely want to test more than one view in this view controller, so you’ll need an easy way to spin the view controller you intend on testing.</p><pre><strong>struct</strong> ViewControllerFactory {<br>    func createInCallVC(frame: CGRect) -&gt; InCallViewController {<br>        let inCallVC = InCallViewController()</pre><pre>        inCallVC.viewWillAppear(false)<br>        inCallVC.layoutIfNeeded()</pre><pre><strong>        return</strong> inCallVC<br>    }<br>}</pre><h4>b) Define device dimensions.</h4><p>It’s essential to be able to <strong>test</strong> <strong>all screen sizes.</strong></p><pre>enum DeviceDimensions {<br>    case iPhoneXSMax, iPhone11ProMax, iPhoneXR, iPhone11<br>    case iPhoneX, iPhoneXS, iPhone11Pro<br>    case iPhone6Plus, iPhone6SPlus, iPhone7Plus, iPhone8Plus<br>    case iPhone6, iPhone6S, iPhone7, iPhone8<br>    case iPhone5, iPhone5S, iPhone5C, iPhoneSE</pre><pre>    // Our views adhere to a safe area not the total point size.<br>    var safeArea: CGRect {<br>        switch self {<br>        case .iPhoneXSMax, .iPhone11ProMax, .iPhoneXR, .iPhone11:<br>            return CGRect(x: 0, y: 44, width: 414, height: 818)<br>        case .iPhoneX, .iPhoneXS, .iPhone11Pro:<br>            return CGRect(x: 0, y: 44, width: 375, height: 734)<br>        case .iPhone6Plus, .iPhone6SPlus, <br>             .iPhone7Plus, .iPhone8Plus:<br>            return CGRect(x: 0, y: 20, width: 414, height: 716)<br>        case .iPhone6, .iPhone6S, .iPhone7, .iPhone8:<br>            return CGRect(x: 0, y: 20, width: 375, height: 647)<br>        case .iPhone5, .iPhone5S, .iPhone5C, .iPhoneSE:<br>            return CGRect(x: 0, y: 20, width: 320, height: 548)<br>        }<br>    }<br>}</pre><pre>// Helper constant to test all possible frame sizes.<br>let safeAreas: [CGRect] = [<br>    DeviceDimensions.iPhoneXSMax.safeArea,<br>    DeviceDimensions.iPhoneX.safeArea,<br>    DeviceDimensions.iPhone6Plus.safeArea,<br>    DeviceDimensions.iPhone6.safeArea,<br>    DeviceDimensions.iPhoneSE.safeArea<br>]</pre><h4>2) Test a particular frame.</h4><pre>func testInCallBodyViewVerticalPosition() throws {<br>    try safeAreas.forEach {<br>        // Given, When<br>        let inCallVC = viewsFactory.createInCallVC(frame: $0)<br>        let bodyView = inCallVC.bodyView</pre><pre>        // Then<br>        let bodyViewMinY = bodyView.frame.minY<br>        let bodyViewMaxY = bodyView.frame.maxY</pre><pre>        XCTAssertEqual(bodyViewMinY, 180)<br>        XCTAssertEqual(bodyViewMaxY, $0.height)<br>    }<br>}</pre><p>Let’s just take a second and unwrap what’s going on here:</p><p>We want to know that no matter the shenanigans are going on around the body view, it will stay put (vertically). We iteratively use our safeAreas and our factory to create our bodyView and compare its frame to that of its superview (in this case the view controller’s view).</p><p>Keep in mind that this example is very simple. If you need to look at a view’s position relative to any of its superview’s superviews, take a look at <a href="https://medium.com/u/76b0105a5cfb">Paul Hudson</a>’s article on <a href="https://www.hackingwithswift.com/example-code/uikit/how-to-convert-a-cgpoint-in-one-uiview-to-another-view-using-convert">How to convert a CGPoint in one UIView to another view using convert()</a>.</p><p>So the tests are written, everything is passing, and next week you change one single margin and…the tests fail. Well great.</p><p>Let’s set a breakpoint and see what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QeTLuCkpUMF4fXsyRrWxVA.png" /></figure><p>Not only is the car safe, but it feels good to drive. Moving us from fragility to stability in one fell swoop. We have written a test that makes sure that our views stay where we want them and gives us an extremely powerful tool in our arsenal when debugging them.</p><h3>Where to go from here</h3><p>How you want to approach your view tests is really up to you and what the needs of your view are. <strong>Don’t go down a rabbit hole of testing every frame of every view</strong>. Test only what is needed. The example test above was testing vertical distance because the in-call view tends to be finicky when modifying heights of the various views that compose it. There would be no point for us to test things like the width of the body view, because even if it did change, it would have no impact on any other view as there are no horizontally related views to the body view.</p><p>One last PSA, at TextNow we have created our own injectable device as our constraint constants are modified slightly for the iPhone SE/5s. This is a great example of setting your view/view controller up in a manner that is injectable. For some info on how to do this with mutable structs have a watch of <a href="https://vimeo.com/nsspain/2018-control-the-world">Stephen Celis’ talk on How To Control The World.</a></p><blockquote><em>“Its so great and I never knew it could be this powerful!”<br></em> — Quinton Pryce, circa September 2020</blockquote><blockquote><em>“love love love love love it”<br> </em>— Anonymous, ibid.</blockquote><p>If you’d like to join Quinton on his quest to test all the things, check out our job openings at <a href="http://textnow.com/careers">TextNow</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51f134bdd0a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/textnowengineering/unit-testing-uiview-frames-51f134bdd0a6">Unit testing UIView frames</a> was originally published in <a href="https://medium.com/textnowengineering">TextNow Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding a layer between you and your analytic tools using Swift]]></title>
            <link>https://medium.com/textnowengineering/adding-a-layer-between-you-and-your-analytic-tools-using-swift-2701d49ce959?source=rss-4d22389a8225------2</link>
            <guid isPermaLink="false">https://medium.com/p/2701d49ce959</guid>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Quinton Pryce]]></dc:creator>
            <pubDate>Mon, 22 Jul 2019 17:37:40 GMT</pubDate>
            <atom:updated>2019-07-22T17:37:40.633Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making analytic tools swappable, mockable, and testable</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_qbLTmygnceaNRE3eipFA.png" /></figure><p>As iOS Developers at TextNow, our dedication to our users requires us to ensure that the use of analytic tools can be maintained and relied on while not interfering with the user’s experience. Whether we are tracking how features perform, obtaining developer metrics, or simply logging data to understand how users interact with our app, analytics has become an integral part of TextNow and many other popular apps and continues to gain traction in the community.</p><p>How analytics are implemented varies from app to app, but one thing always stays the same: when the business’s needs change and a new analytics tool is introduced, the code is always impacted. Attempting to minimize horizontal change was the number one reason we opted for this framework.</p><blockquote>Horizontal change is making many of the same changes across many files in a project.</blockquote><p>Our aim when starting this project was to create a layer between us and the analytic tools that we use. We also aimed to solve the following problems that we saw with current implementation of analytic frameworks:</p><p>1. Lack of testability<br>2. Lack of mockability<br>3. View controller bloat<br>4. Difficulty juggling multiple tools</p><p>In this article, we will show how we built this analytic layer and the design decisions around the features we added to it.</p><blockquote>If you are looking to implement this framework and would like to learn how please visit our G<a href="https://github.com/textnow/Analytics-iOS/?source=post_page---------------------------#analyticlayer">itHub page</a>.</blockquote><h3>High level component diagram</h3><p>To help with understanding how each piece fits together, we thought it’d be best to present it in a diagram. We suggest referring to this as you move through the article to give context to each component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUJgn4hf4qoZNnub4jMdzg.png" /></figure><p>We kicked off our implementation with the most important part of the framework: the layer between us and our tools. We have generalized all analytic tools as EventTrackers. EventTrackers are responsible for understanding how to dispatch events to any tool you decide to use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fefe5f224ba4040cd0b73cfce14be007/href">https://medium.com/media/fefe5f224ba4040cd0b73cfce14be007/href</a></iframe><p>The first two methods are used to track a single event, or an event with parameters. The third method here was a feature to check if an event name is supported by the wrapped analytic tool. In many cases you will swap which events dispatch to which tools and some tools have specific guidelines on the format of their event strings. Often these tools fail too gracefully, not alerting you that an event has not been tracked due to the malformation of the string.</p><p>For example, <a href="https://www.adjust.com/">Adjust</a> uses a very specific id string for its events:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/771f7f05d91430623e6fcea4ba77aa15/href">https://medium.com/media/771f7f05d91430623e6fcea4ba77aa15/href</a></iframe><p>As we can see, contracting EventTrackers to implement isEventNameSupported will prevent us from tracking events to tools like Adjust that do not support all string configurations.</p><h3>Creating Events</h3><p>All analytic tools, at the very least, have some string-based event that allows you to track certain metrics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b0d132e5f765fbcbccbf5a4b5e26bfc/href">https://medium.com/media/4b0d132e5f765fbcbccbf5a4b5e26bfc/href</a></iframe><p>AnalyticsEvent wraps up event names and provides us with the supportedTrackers variable. The added variable lifts the responsibility of which event dispatches to which tool from our code (or view controllers in many cases), to our event implementation. Pulling out the responsibility of which tool an event tracks to from our view controller helps us reduce horizontal edits when tools change, and aids in bloat reduction in our view controllers.</p><p>Not only does the supportedTrackers variable reduce bloat, but this makes managing multiple tools much easier. From simply looking at it, you can see which event is dispatched to which tool and quickly make large edits in only one or two files.</p><h3>Adding additional data to our events</h3><p>In many cases, especially for developer metrics, you will want to track more than just a simple string. For this scenario, we have created the AnalyticsParameter protocol. This allows clients to implement any parameter type that they might need for any type of tool.</p><p>Many tools use a simple [AnyHashable: Any] hash table but there are situations where we may require a parameter to be a different type. For example, <a href="https://www.leanplum.com/?source=post_page---------------------------">Leanplum</a> (a mobile engagement platform) has a method track(event: String, withValue: Double) which tracks an event with a Double<em> </em>as the ‘parameter’. Providing the client-defined parameter types was a decision made to allow features (like the one Leanplum has created) to still be usable with this layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15bbafb70f487590a76cb4e2ffb609f6/href">https://medium.com/media/15bbafb70f487590a76cb4e2ffb609f6/href</a></iframe><p>AnalyticsParameter gives us the freedom to track absolutely any type of data.</p><p>An example showing how you can leverage this flexibility can be seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf134e59051f5500a1414782de7afe1/href">https://medium.com/media/edf134e59051f5500a1414782de7afe1/href</a></iframe><p>We have removed more bloat with this implementation by delegating the responsibility of unwrapping to a type that your tool can understand out of our view controllers and into our implementation of parameters.</p><h3>Using multiple tools</h3><p>As we saw previously in the AnalyticsEvent, we have supportedTrackers which is an array of strings to allow the core engine to know which tool each event is supposed to be dispatched to. We call these strings EventTrackerKeys and they are what the core of this framework uses to hash the initialized EventTrackers and store them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b42cdff71199e31ef44b810af20e9d68/href">https://medium.com/media/b42cdff71199e31ef44b810af20e9d68/href</a></iframe><h3>The Core</h3><p>The core of this framework is what puts all the pieces together. It holds reference to our EventTracker(s), it dispatches events (and parameters) to the proper tools and performs validation on events to ensure they are tracked properly.</p><p><strong>1) Send events (and parameters) to the </strong><strong>EventTracker(s), keyed by the event’s </strong><strong>supportedTrackers variable:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4cf428f3fd060740de32e806444f8ec/href">https://medium.com/media/e4cf428f3fd060740de32e806444f8ec/href</a></iframe><p>Keyed by our EventTrackerKey<em>,</em> we store our EventTracker(s) in a pre-initialized hash table. We don’t need clients reading the eventTrackers array, and we also don’t want clients to worry about thread safety so we implement the method addEventTracker(:).</p><p><strong>2) Send events (and parameters) to the </strong><strong>EventTracker(s), keyed by the event’s </strong><strong>supportedTrackers variable:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecc7fef6cf871cfa3aff50400ca5dd74/href">https://medium.com/media/ecc7fef6cf871cfa3aff50400ca5dd74/href</a></iframe><p>We want to expose two simple methods to the client, track an event, and track an event with parameters. Under the hood, they will execute very similar code and in order to support our generics, the parameters must have a type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55c344702ae31024055be54491c3c10e/href">https://medium.com/media/55c344702ae31024055be54491c3c10e/href</a></iframe><p>Now that our code that dispatches events is in one place, we can take a look at adding some error handling to it.</p><p><strong>3) Validate that each of the </strong><strong>AnalyticsEvent’s </strong><strong>supportedTrackers have been added to the core using </strong><strong>addEventTracker(:):</strong></p><p>By default, we want to be aggressive about failing test conditions, but we also want to allow clients to define their own failure handlers if they are so inclined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdbe5e0b83450483cf6d88b98daa7a4a/href">https://medium.com/media/fdbe5e0b83450483cf6d88b98daa7a4a/href</a></iframe><p>Now that we have the default FailureHandler abiding by the protocol we can write the initializers for the core.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0019fbf1397f2dd1f2a60f56004b145c/href">https://medium.com/media/0019fbf1397f2dd1f2a60f56004b145c/href</a></iframe><p>In many cases it takes some time for certain tools to initialize and tracking events before this time can cause unanticipated results. We want to prevent that by adding the following conditions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/706b97e3fe627868b152160bcd74d864/href">https://medium.com/media/706b97e3fe627868b152160bcd74d864/href</a></iframe><p>Preventing events from being dispatched that are EventTracker-less or contain an EventTracker that has not been added to our core will ensure that events that are sent to the core actually get tracked. Using these two conditions we can be certain that events are being properly sent to their respective EventTracker(s).</p><p><strong>4) Validate the </strong><strong>AnalyticsEvent follows the </strong><strong>EventTracker‘s event name support with the </strong><strong>isEventNameSupported(:) method:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d442a61f46be46629580a085980c32d7/href">https://medium.com/media/d442a61f46be46629580a085980c32d7/href</a></iframe><p>Adding the final condition will ensure the event name that is being tracked is supported by it’s keyed EventTracker. As mentioned above, this will avoid issues when dispatching events to your analytic tool(s) that are unsupported.</p><h3>Final Touches</h3><p>Now that we have the logic in place, we will make one final addition to the core to ensure that it is mockable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efce7f100b2464470a048bbfdfe59838/href">https://medium.com/media/efce7f100b2464470a048bbfdfe59838/href</a></iframe><p>Clients can either use the singleton pattern that the framework has baked in: public static let shared: AnalyticsScope = Analytics() or they can manage access to it themselves.</p><p>Putting all of this together we have our final engine that will process all events/parameters and store our EventTracker(s).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5de9a74fe1acd3bb9d8fd7fc3b709ea/href">https://medium.com/media/f5de9a74fe1acd3bb9d8fd7fc3b709ea/href</a></iframe><h3>Wrap up</h3><p>Analytics will continue to change throughout the life of our applications, and we need to be prepared for it. Becoming reliant on a single tool can make it harder to move toward something new that may serve our apps better. Adding a layer between us and the analytic tools we use will most certainly pay off. If not for the ability to swap out tools, we should be doing it for the testability. We want to be able to rely on the data that we track even if we are the primary consumers of that data.</p><p>If you are wanting to know more about how to implement this framework, please check out our <a href="https://github.com/textnow/Analytics-iOS/?source=post_page---------------------------">GitHub page</a>. The steps to install are in the <a href="https://github.com/textnow/Analytics-iOS/blob/master/README.md">README</a> and there is more information on how you might use this framework in the <a href="https://github.com/textnow/Analytics-iOS/wiki/Usage-and-Implementation">Wiki</a>. Along with the docs there is a sample app that implements this framework to give you some ideas on how to best implement it.</p><blockquote>If you want to learn more about the work we do at TextNow and where you might fit in, check out our <a href="https://about.textnow.com/careers/">careers page</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2701d49ce959" width="1" height="1" alt=""><hr><p><a href="https://medium.com/textnowengineering/adding-a-layer-between-you-and-your-analytic-tools-using-swift-2701d49ce959">Adding a layer between you and your analytic tools using Swift</a> was originally published in <a href="https://medium.com/textnowengineering">TextNow Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>