<?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[Device Blogs - Medium]]></title>
        <description><![CDATA[Thoughts on building products, engineering, design and development - Medium]]></description>
        <link>https://medium.com/device-blogs?source=rss----75b2e3c15714---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Device Blogs - Medium</title>
            <link>https://medium.com/device-blogs?source=rss----75b2e3c15714---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:18:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/device-blogs" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[All you never wanted to know about state in SwiftUI]]></title>
            <link>https://medium.com/device-blogs/all-you-never-wanted-to-know-about-state-in-swiftui-7314d0c51318?source=rss----75b2e3c15714---4</link>
            <guid isPermaLink="false">https://medium.com/p/7314d0c51318</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[home]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Peter Livesey]]></dc:creator>
            <pubDate>Mon, 09 Dec 2019 15:29:28 GMT</pubDate>
            <atom:updated>2019-12-09T15:29:28.309Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently released <a href="https://apps.apple.com/us/app/id1480388057">an app</a> written 100% in SwiftUI and in doing so, uncovered some patterns that are difficult to express. In this post, I am going to explain how to set initial state in SwiftUI. It’s trickier than you’d expect.</p><h3>First, an overview</h3><p>There are three types of local state in SwiftUI:</p><ol><li>State that’s only controlled by this view</li><li>State that’s only controlled by a parent</li><li>State that’s controlled by both this view and its parent</li></ol><p>There’s also external state with environment variables and observables, but I’m going to ignore these in this post for brevity.</p><h4>State controlled by this view</h4><p>If you have some local state to keep track of, this is easy:</p><pre>struct MyView: View {<br>  @State private var toggleSelected = false<br>  ...</pre><p>This state can now be changed by MyView which will rerender whenever toggleSelected is edited. This state can be passed down to child views, but a parent cannot edit this state.</p><h4>State controlled by a parent</h4><p>Often, you want a parent view to control a variable without letting the child view edit it. This can be done with a simple instance variable.</p><pre>struct MyView: View {<br>  let text: String<br>  ...<br>}</pre><pre>struct ParentView: View {<br>  @State private var text = &quot;hello&quot;</pre><pre>  var body: some View {<br>    MyView(text: text)<br>  }<br>}</pre><p>At first glance, it may appear that text is immutable since it’s declared with let. However, whenever text on the parent changes, it will call body again and recreate a new instance of MyView with a new text value. This allows the parent to control the state of a child without allowing the child to edit this value.</p><h4>State controlled by both the parent and child</h4><p>And finally, sometimes you want state to be controlled by both the parent and the child. For this, you use a binding:</p><pre>struct MyView: View {<br>  @Binding var text: String<br>  ...<br>}</pre><pre>struct ParentView: View {<br>  @State private var text = &quot;&quot;</pre><pre>  var body: some View {<br>    MyView(text: $text)<br>  }<br>}</pre><p>Now, both the parent and child can change the value of text and they share this value. If either the parent change the value of text both views will rerender.</p><h3>A need for something different</h3><p>In my app, ZenDen, there’s a feature where you can reassign a task to someone else in your home. This view needs to keep track of which person is selected but it only actually changes if you tap save. So, it makes sense that only the child keeps track of this state. When you tap save, you can simply inform the parent view of this change through a completion block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*jovpUYj_zHsR1eVy4Un0MA.png" /><figcaption>Users can reassign a task to someone else. If you select ‘Keep it fair’, it will automatically reassign future tasks to keep the load even.</figcaption></figure><p>Here’s the code so far:</p><pre>struct ReassignView: View {<br>  // Called with the selected assignee and keep it fair on save<br>  let saveTapped: (String, Bool) -&gt; Void<br>  @State var selectedAssignee = &quot;Anyone&quot;<br>  ...<br>}</pre><p>But there’s a product problem here. Currently, the view will always initialize selectedAssignee with Anyone . But, I wanted to set an initial value which is the current assignee for the task. So, if the task is currently assigned to me, I want the reassign view to pop up and show Peter as the selected assignee. I want to initialize the child’s state with an initial value. You’d think this would be easy by simply passing it in the initializer:</p><pre>struct ReassignView: View {<br>  @State var selectedAssignee = &quot;&quot;</pre><pre>  init(assignee: String) {<br>    selectedAssignee = assignee<br>  }<br>}</pre><p>Sadly, this <em>just doesn’t work</em>. No matter what you pass in as assignee, selectedAssignee will always be initialized to empty string. I can only speculate why this is the case, but it seems like @State can only be mutated outside of the init. Luckily, there’s a workaround:</p><pre>struct ReassignView: View {<br>  @State var selectedAssignee: String</pre><pre>  init(assignee: String) {<br>    _selectedAssignee = State(initialValue: assignee)<br>  }<br>}</pre><p>_selectedAssignee is a trick to access the wrapper object instead of the string. It has the type State&lt;String&gt; and here, it’s initialized with the assignee. Now, when it’s first initialized, the parent can control the initial value. After that, the ReassignView will control the value of selectedAssignee.</p><h3>But wait, there’s a bug?</h3><p>Consider the following code:</p><pre>// in the parent<br>var body: some View {<br>  ReassignView(assignee: &quot;Peter&quot;)<br>}</pre><ol><li>The parent creates the ReassignView with the initial value “Peter”</li><li>The ReassignView changes its internal state to “Alice”</li><li>The parent is rerendered for some reason (e.g. some unrelated state has changed)</li><li>init will be called on ReassignView and the assignee will be set back to “Peter”</li></ol><p>Won’t this cause a bug?</p><p><strong>Actually, no, it won’t.</strong> To understand why, we need to understand how SwiftUI injects state into View objects. Although SwiftUI is closed source and the documentation is currently non-existent, it seems to follow this sequence of events:</p><ol><li>Call init on the View</li><li>If there’s stored state for this view, set all the @State properties</li><li>Call body on the View</li></ol><p>So, even though in init, we set the initial value of selectedAssignee, this is always overridden before body is called if it’s previously been set. In this case, selectedAssignee will indeed be initialized with the value “Peter”, but it will be changed to “Alice” before body is called.</p><h3>But wait, isn’t this an antipattern?</h3><p>The main problem I have with this approach is that it’s not clear to the parent view that this is the behavior. The initializer looks identical to an initializer when the state is controlled by the parent. Consider these two side by side:</p><pre>Text(myText)<br>ReassignView(assignee: myAssignee)</pre><p>If myText changes, then the text will rerender on screen. However, if myAssignee changes, it will not update the ReassignView. Since this new view behaves differently from the stock SwiftUI views, one might consider this an antipattern.</p><p>I’ve adopted the convention of prefixing all of these initializer arguments with initial so the initializer becomes:</p><pre>ReassignView(initialAssignee: myAssignee)</pre><p>SwiftUI is still new and so it’s up to us (the community) to define conventions like this. Let me know in the comments what you think of this convention and if you have other ideas.</p><h3>Other ways to accomplish this</h3><p>Instead of this approach, you could simply make selectedAssignee a binding. However, this feels like it leaks implementation details to the parent since it doesn’t need to ever read this value. It also now needs to worry about resetting this value at the correct time (whenever a new ReassignView is presented). Ultimately, I think this makes it a worse approach.</p><p>You could also avoid setting the State with a default value:</p><pre>struct ReassignView: View {<br>  let initialAssignee: String<br>  @State private var storedAssignee: String? = nil<br>  private var selectedAssignee: String {<br>    get { storedAssignee ?? initialAssignee }<br>    set { storedAssignee = newValue }<br>  }<br>}</pre><p>However, this still falls to the same antipattern problems as my approach and requires significantly more boilerplate.</p><h3>Phew…that was crazy…</h3><p>Welcome to SwiftUI! 😛 It’s <a href="https://www.rei.com/blog/climb/fun-scale">fun</a>.</p><p>We’ve just released our <a href="https://apps.apple.com/us/app/id1480388057">new app — ZenDen</a>, and it’s written entirely with SwiftUI. If you have any questions about writing a production app in SwiftUI, let me know in the comments. I’m planning on writing a few more posts on SwiftUI, so let me know what to write next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*CBvd25rH3VphDw4b0SA-nw.png" /><figcaption>Find some Zen with ZenDen</figcaption></figure><p>We wrote ZenDen to reduce the stress caused by organizing household tasks. The mental load of organizing a home often unfairly falls on one individual when most of this organization can be automated.</p><p>We’re always trying to improve, so let us know if you have any feedback on the app.</p><p>Thanks to Felix Lapalme for helping review this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7314d0c51318" width="1" height="1" alt=""><hr><p><a href="https://medium.com/device-blogs/all-you-never-wanted-to-know-about-state-in-swiftui-7314d0c51318">All you never wanted to know about state in SwiftUI</a> was originally published in <a href="https://medium.com/device-blogs">Device Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Advanced Features to your Network Stack in Swift]]></title>
            <link>https://medium.com/device-blogs/adding-advanced-features-to-your-network-stack-in-swift-941ecfff8dc3?source=rss----75b2e3c15714---4</link>
            <guid isPermaLink="false">https://medium.com/p/941ecfff8dc3</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Peter Livesey]]></dc:creator>
            <pubDate>Thu, 15 Aug 2019 15:33:31 GMT</pubDate>
            <atom:updated>2019-08-29T14:19:43.699Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is part 2 of a series in writing an elegant and extensible network stack in Swift. You can read </em><a href="https://medium.com/device-blogs/writing-an-elegant-and-extensible-network-stack-in-swift-e2f5d9ab3ea9"><em>part 1 here</em></a><em>.</em></p><p>Writing your own networking stack is easy! One of the main advantages of owning your stack is that it’s simple to add additional features. You can pick and choose what you add depending on the specific needs of your application. You don’t need your stack to support every feature anyone could think of, but if you own your code, you can easily add in features when appropriate.</p><p>In this post, I’ll show a few examples of extending an existing stack. You may find some examples useful, while others may inspire you to add something else. Specifically, we’ll add:</p><ul><li>A DataConvertible protocol which will make returning non-models possible</li><li>The ability to cancel requests</li><li>Support for downloading files to disk</li><li>Background tasks</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*n8X7CQDfev1hP8JAIHaMeQ.jpeg" /><figcaption>Just keep adding features until you’ve got what you need. But hopefully, designed better than this. (Source: Buzzfeed)</figcaption></figure><h3>What we have so far</h3><p>In <a href="https://medium.com/device-blogs/writing-an-elegant-and-extensible-network-stack-in-swift-e2f5d9ab3ea9">part 1</a>, we built a simple networking stack which could handle GET and POST requests which also handled model parsing, status code errors and threading.</p><ol><li>It creates a URLRequestfrom a Requestable object</li><li>It creates a task and starts it</li><li>In the completion block, it checks for errors and then parses the Data into a model</li></ol><p>You can view <a href="https://github.com/plivesey/Network/blob/master/Network/Network/SimpleNetwork.swift">the full starter code here</a>, but here’s a condensed version:</p><pre>class Network {<br>  static let shared = Network()</pre><pre>  let session: URLSession = URLSession(configuration: .default)</pre><pre>  private let queue = DispatchQueue(label: &quot;Network&quot;, qos: .userInitiated, attributes: .concurrent)</pre><pre>  func send&lt;T: Model&gt;(_ request: Requestable, completion: <a href="http://twitter.com/escaping">@escaping</a> (Result&lt;T, Error&gt;)-&gt;Void) {<br>    queue.async {<br>      let urlRequest = request.urlRequest()</pre><pre>      // Send the request<br>      let task = self.session.dataTask(with: urlRequest) { data, response, error in<br>        let result: Result&lt;T, Error&gt;</pre><pre>        if let error = error {<br>          // First, check if the network just returned an error<br>          result = .failure(error)<br>        } else if let error = self.error(from: response) {<br>          // Next, check if the status code was valid<br>          result = .failure(error)<br>        } else if let data = data {<br>          // Otherwise, let&#39;s try parsing the data<br>          do {<br>            let decoder = JSONDecoder()<br>            result = .success(try decoder.decode(T.self, from: data))<br>          } catch {<br>            result = .failure(error)<br>          }<br>        } else {<br>          Log.assertFailure(&quot;Missing both data and error&quot;)<br>          result = .failure(NetworkError.noDataOrError)<br>        }</pre><pre>        DispatchQueue.main.async {<br>          completion(result)<br>        }<br>      }</pre><pre>      task.resume()<br>    }<br>  }<br>}</pre><h3>Data Convertible</h3><p>One problem with the current stack is that network requests always return a Model. This is the main use-case, but what if the network request doesn’t return anything? Or it returns binary data such as an image?</p><p>You have a couple of options. You could write a separate send function for each use-case, but you’d end up with a lot of duplicated code. Instead, let’s try a protocol-oriented approach:</p><pre>protocol DataConvertible {<br>  static func convert(from data: Data?) throws -&gt; Self<br>}</pre><pre>protocol RequiredDataConvertible: DataConvertible {<br>  static func convert(from data: Data) throws -&gt; Self<br>}</pre><pre>extension RequiredDataConvertible {<br>  static func convert(from data: Data?) throws -&gt; Self {<br>    if let data = data {<br>      return try convert(from: data)<br>    } else {<br>      throw DataConversionError(&quot;Missing data&quot;)<br>    }<br>  }<br>}</pre><p>For most types, it’s useful to convert non-optional Data, so there’s a wrapper protocol, RequiredDataConvertible for convenience. We can change our send function to:</p><pre>func send&lt;T: DataConvertible&gt;(_ request: Requestable, completion: <a href="http://twitter.com/escaping">@escaping</a> (Result&lt;T, Error&gt;)-&gt;Void) {<br>  // ...<br>  } else {<br>    do {<br>      result = .success(try T.convert(from: data))<br>    } catch {<br>      result = .failure(error)<br>    }</pre><p>And now, we can make any type we want adhere to DataConvertible.</p><pre>extension Data: RequiredDataConvertible {<br>  static func convert(from data: Data) throws -&gt; Data {<br>    return data<br>  }<br>}</pre><pre>// You can use this to return no data<br>struct Empty: DataConvertible {<br>  static func convert(from data: Data?) throws -&gt; Empty {<br>    return Empty()<br>  }<br>}</pre><p>You could also easily add support for strings, images, dictionaries, arrays, or anything else your app may need.</p><p>Sadly, making Decodable is a little trickier as you can’t simply extend Decodable to be DataConvertible. Data is also Decodable, so you end up with ambiguous types. To get around this, we need to use type erasure:</p><pre>struct DecodableConvertible&lt;T: Model&gt;: RequiredDataConvertible {<br>  let model: T</pre><pre>  init(_ model: T) {<br>    self.model = model<br>  }</pre><pre>  static func convert(from data: Data) throws -&gt; DecodableConvertible&lt;T&gt; {<br>    let decoder = JSONDecoder()<br>    let model = try decoder.decode(T.self, from: data)<br>    return DecodableConvertible(model)<br>  }<br>}</pre><p>And then we need to add another send method to Network:</p><pre>func send&lt;T: Model&gt;(_ request: Requestable, completion: <a href="http://twitter.com/escaping">@escaping</a> (Result&lt;T, Error&gt;)-&gt;Void) {<br>  return send(request) { (result: Result&lt;DecodableConvertible&lt;T&gt;, Error&gt;) in<br>    // We want to return T, so we should map to the inner model<br>    completion(result.map { $0.model })<br>  }<br>}</pre><p>Effectively, we’re creating a wrapper struct to hold the inner model. Then, we return this struct from the network stack and map out the inner model. The type erasure technique is common, and you can <a href="https://medium.com/swiftworld/swift-world-type-erasure-5b720bc0318a">learn more about it here</a>.</p><p>By the way, this type erasure is the reason why we need the Model protocol (<a href="https://medium.com/device-blogs/writing-an-elegant-and-extensible-network-stack-in-swift-e2f5d9ab3ea9">remember how we used that instead of </a><a href="https://medium.com/device-blogs/writing-an-elegant-and-extensible-network-stack-in-swift-e2f5d9ab3ea9">Decodable for the models?</a>). Now, if you pass in a Model as a return type, it will use the DecodableConvertible struct, but if you pass in Data, it will use the extension on Data to do the conversion. That may seem like a lot to follow, but if you’re confused, try <a href="https://github.com/plivesey/Network">checking out the code</a> and use Decodable instead of Model.</p><h3>Cancelling Requests</h3><p>NSURLSession allows cancelling of requests, but currently, our network stack does not. We can’t simply return a URLSessionTask because our stack is completely asynchronous (which is a good thing). There’s a solution though — we just need to write a class to handle canceling before the request is sent.</p><pre>class NetworkTask {<br>  private var task: URLSessionTask?<br>  private var cancelled = false</pre><pre>  private let queue = DispatchQueue(label: &quot;com.peterlivesey.networkTask&quot;, qos: .utility)</pre><pre>  func cancel() {<br>    queue.sync {<br>      cancelled = true</pre><pre>      // If we already have a task cancel it<br>      if let task = task {<br>        task.cancel()<br>      }<br>    }<br>  }<br>  <br>  func set(_ task: URLSessionTask) {<br>    queue.sync {<br>      self.task = task</pre><pre>      // If we&#39;ve cancelled the request before the task was set, let&#39;s cancel now<br>      if cancelled {<br>        task.cancel()<br>      }<br>    }<br>  }<br>}</pre><p>This class simply saves the cancel request and once the task is set, it will cancel it immediately. The only thing to remember is to use a DispatchQueue to keep everything thread-safe. Then, just update the send function:</p><pre>func send&lt;T: DataConvertible&gt;(...) -&gt; NetworkTask {<br>  <strong>let</strong> networkTask = NetworkTask()<br>  queue.async {<br>    // ...<br>    task.resume()<br>    networkTask.set(task)<br>  }<br>  return networkTask<br>}</pre><p>Though that session task is set asynchronously, we can immediately return our empty task since it can be cancelled at any time.</p><h3>Adding Background Tasks</h3><p>When your app goes to the background, usually all network tasks are cut off. This creates a really bad user experience. If users switch apps quickly, they’ll see error messages when they return to the app. Luckily, Apple provides a really easy API to solve this, and you can add it directly into the stack for every request. Just add to your send method:</p><pre>func send(...) {<br>  let backgroundTaskID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)<br>  // ... after all the main logic, when you finish:<br>  DispatchQueue.main.async {<br>    completion(result)<br>    UIApplication.shared.endBackgroundTask(backgroundTaskID)<br>  }<br>}</pre><h3>File Download Support</h3><p>File downloading is similar to downloading data, but it has a slightly different API. You could simply copy-paste your existing code and change the necessary lines, but I prefer to share the code.</p><p>This is a little tricky, but possible with some creative closures. First, we need to change our send method slightly and also make it private (because this API isn’t exactly user friendly):</p><pre>private func send&lt;DataType, ReturnType&gt;<br>(_ request: Requestable,<br> taskCreator: <a href="http://twitter.com/escaping">@escaping</a> ((URLRequest, <a href="http://twitter.com/escaping">@escaping</a> (DataType?, URLResponse?, Error?)-&gt;Void)-&gt;URLSessionTask),<br> dataConvertor: <a href="http://twitter.com/escaping">@escaping</a> (DataType?) throws -&gt; ReturnType,<br> completion: <a href="http://twitter.com/escaping">@escaping</a> (Result&lt;ReturnType, Error&gt;)-&gt;Void)<br> -&gt; NetworkTask {</pre><p>Let’s decode what’s happened here:</p><ul><li>There’s an additional generic parameter: DataType</li><li>The first parameter is still just the request</li><li>The second parameter is a closure which converts a URLRequest and completion block into a data task</li><li>The third parameter is a closure which converts a DataType into a ReturnType</li><li>The final parameter is the completion block</li></ul><p>Now, let’s convert our original send function to use this helper function.</p><pre>func send&lt;T: DataConvertible&gt;(request, completion) -&gt; NetworkTask {<br>  return send(<br>    request,<br>    taskCreator: { session.dataTask(with: $0, completionHandler: $1) },<br>    dataConvertor: { try T.convert(from: $0) },<br>    completion: completion<br>  )<br>}</pre><p>The second parameter creates a data task from the session object. This is just a one-liner. The third parameter simply calls the DataConverible convert function.</p><p>We can write a similar function to wrap download requests:</p><pre>func download<br>(_ request: Requestable,<br> destination: URL,<br> completion: <a href="http://twitter.com/escaping">@escaping</a> (Result&lt;Empty, Error&gt;)-&gt;Void) -&gt; NetworkTask<br>{<br>return send(<br>  request,<br>  taskCreator: { session.downloadTask(with: $0, completionHandler: $1) },<br>  dataConvertor: { try self.moveFile(from: $0, to: destination) } },<br>  completion: completion)<br>}</pre><p>This function takes a request and a destination URL and downloads a file to that location. The second parameter creates a download task instead of a data task. The third parameter takes the temporary URL returned by the download task and <a href="https://github.com/plivesey/Network/blob/master/Network/Network/Network.swift#L158">moves the file from that location to the passed in location</a>.</p><p>Now, you just need to update the send code to use these task creator and data convertor tasks. This is relatively simple, but if you’re interested in the details, <a href="https://github.com/plivesey/Network">you can check out the full code here</a>.</p><h3>Other Ideas</h3><p>Remember, you don’t need to add any of these features if it’s not appropriate for your app. These are only examples of things you may want to add.</p><p>When building the <a href="https://apps.apple.com/us/app/navigator-meeting-assistant/id1466919451">Navigator app</a>, I added even more features including redirect handling, unzip support for files, and parsing custom errors. (If you’re interested in working with a stack like that, <a href="https://aspen.team/careers/">they’re hiring</a>).</p><p>The key takeaway here is that if you own your network stack, <em>it’s yours</em>. You can mold it into whatever your app needs.</p><p><em>This project and article will need to evolve as Swift and Foundation change. If you have any suggestions, comments, improvements, bugs, please let me know in the comments or </em><a href="https://github.com/plivesey/Network/pulls"><em>submit a PR to the Github project</em></a><em>.</em></p><p><em>Thanks to Alice Avery and </em><a href="https://twitter.com/kamilah"><em>Kamilah Taylor</em></a><em> for reviewing this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=941ecfff8dc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/device-blogs/adding-advanced-features-to-your-network-stack-in-swift-941ecfff8dc3">Adding Advanced Features to your Network Stack in Swift</a> was originally published in <a href="https://medium.com/device-blogs">Device Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing an Elegant and Extensible Network Stack in Swift]]></title>
            <link>https://medium.com/device-blogs/writing-an-elegant-and-extensible-network-stack-in-swift-e2f5d9ab3ea9?source=rss----75b2e3c15714---4</link>
            <guid isPermaLink="false">https://medium.com/p/e2f5d9ab3ea9</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Peter Livesey]]></dc:creator>
            <pubDate>Sat, 10 Aug 2019 19:24:40 GMT</pubDate>
            <atom:updated>2019-08-29T14:18:02.675Z</atom:updated>
            <content:encoded><![CDATA[<p>Apple constantly updates their networking APIs to make them easier to use. However, I find that a lot of people still are hesitant to write their own networking layer and choose to rely on common open source solutions.</p><p>Writing your own networking stack has several benefits. To name just a few:</p><ul><li>Avoids a 3rd party dependency which will need upgrading</li><li>More understandable code (since you wrote it!)</li><li>More extensible</li><li>Easier to debug, add logs, and add performance monitoring</li><li>Much easier to add advanced functionality</li><li>Allows you to parse errors from your backend into a specific model</li><li>Makes it easy to support custom error handling such as 401 or 500 status codes</li></ul><p>Plus, it’s now just really easy! In this article, I’m going to go over the basics. By the end of this post, you’ll have a network stack that can easily send GET and POST requests with model parsing with little boilerplate.</p><pre>let request = Request(path: &quot;users/1&quot;)<br>Network.shared.send(request) { (result: Result&lt;User, Error&gt;) in<br>  switch result {<br>    case .success(let user):<br>      print(user)<br>    case .failure(let error):<br>      print(error)<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*WWX1aNqa8Bzhqu_2OD0L7w.jpeg" /><figcaption>With codable, NSURLSession, and generics, writing your own networking stack is easier than ever</figcaption></figure><p>In a follow-up post, I’ll show how you can upgrade this simple network stack with more advanced features such as background tasks, file downloads, cancelable requests, and more.</p><h3>Setup</h3><p>First, let’s create a new file, Network.swift and add a singleton accessor, a session variable, and a basic send function:</p><pre><strong>class</strong> Network {<br>  <strong>static</strong> <strong>let</strong> shared = Network()<br>  <strong>let</strong> session: URLSession = URLSession(configuration: .default)</pre><pre><strong>  func</strong> send(<strong>_</strong> request: URLRequest,<br>            completion: <strong>@escaping</strong> (Result&lt;Data, Error&gt;)-&gt;Void) {}<br>}</pre><p>The send function takes a request and a completion block which returns a Result with either data or an error. Now, let’s fill this in with a simple implementation:</p><pre>Log.verbose(&quot;Send: \(urlRequest.url?.absoluteString ?? &quot;&quot;)&quot;)</pre><pre><strong>let</strong> task = session.dataTask(with: request) { data, response, error <strong>in</strong><br>  let result: Result&lt;T, Error&gt;<br>  if let error = error {<br>    // First, check if the network just returned an error<br>    result = .failure(error)<br>  } else if let data = data {<br>    result = .success(data)<br>  } else {<br>    Log.assertFailure(&quot;Missing both data and error from NSURLSession.&quot;)<br>    result = .failure(NetworkError.noDataOrError)<br>  }</pre><pre>  DispatchQueue.main.async {<br>    completion(result) <br>  }<br>}</pre><pre>// Make sure to call resume on the task or nothing will happen!<br>task.resume()</pre><p>Most of the code here is straightforward, but you’ll notice a couple of interesting things about this implementation:</p><ol><li>I created a simple NetworkError enum for some basic errors.</li><li>I’ve added some Log statements to the code. This is one of the benefits of your own networking stack! You can add your own Log statements where you see fit. <a href="https://github.com/plivesey/Network/blob/master/Network/Log/Log.swift">Here’s my implementation</a> or <a href="https://medium.com/device-blogs/assertions-in-production-e587fef5bfbc">previous post on assertions in code</a>.</li></ol><h3>Models</h3><p>This send function works fine, but it isn’t much better than just using URLSession directly. In most cases, we don’t want Data returned, but a model. So, let’s add a Model protocol and add support for parsing.</p><pre><strong>protocol</strong> Model: Codable {}</pre><p>It’ll become clear in a future post why we create this empty protocol instead of using Codable directly. Just trust me for now.</p><pre><strong>func</strong> send&lt;T: Model&gt;(<strong>_</strong> request: URLRequest, completion: <strong>@escaping</strong> (Result&lt;T, Error&gt;)-&gt;Void) {</pre><pre>...</pre><pre>} else if let data = data {<br>  do {<br>    let decoder = JSONDecoder()<br>    result = .success(try decoder.decode(T.self, from: data))<br>  } catch {<br>    result = .failure(error)<br>  }<br>}</pre><p>Simple. We just change the send function to be generic and add the JSONDecoder handling. When we call this function, we’ll be returned a model to immediately use in application code.</p><h3>Better Requests</h3><p>The URLRequest object is a little verbose to use, so instead, let’s create a wrapper object to make creating requests easier. Instead of using inheritance, I prefer a protocol-oriented architecture:</p><pre>protocol Requestable {<br>  func urlRequest() -&gt; URLRequest<br>}</pre><pre>struct Request: Requestable {<br>  let path: String<br>  let method: String</pre><pre>  init(path: String, method: String = &quot;GET&quot;) {<br>    self.path = path<br>    self.method = method<br>  }</pre><pre>  func urlRequest() -&gt; URLRequest {<br>    guard let url = URL(string: &quot;BASE_URL&quot;) else {<br>      Log.assertFailure(&quot;Failed to create base url&quot;)<br>      return URLRequest(url: URL(fileURLWithPath: &quot;&quot;))<br>    }</pre><pre>    var request = URLRequest(url: url.appendingPathComponent(path))<br>    request.httpMethod = method</pre><pre>    return request<br>  }<br>}</pre><pre>extension URLRequest: Requestable {<br>  func urlRequest() -&gt; URLRequest { return self }<br>}</pre><p>This new Request object includes the base url for your server so you can simply specify a path and a method. We can also easily make URLRequest adhere to Requestable in case we do want to make requests to other servers.</p><p>Updating our send method to use this new protocol is trivial:</p><pre><strong>func</strong> send&lt;T: Model&gt;(<strong>_</strong> request: Requestable, completion: <strong>@escaping</strong> (Result&lt;T, Error&gt;)-&gt;Void) {<br>  let urlRequest = request.urlRequest()<br>  ...</pre><h3>Post Requests</h3><p>When sending a POST request, you often send JSON data as part of the request. Of course, we don’t want to format that ourselves. How about using a Model? Let’s add a PostRequest struct:</p><pre>struct PostRequest&lt;Model: Encodable&gt;: Requestable {<br>  let path: String<br>  let model: Model</pre><pre>  func urlRequest() -&gt; URLRequest {<br>    guard let url = URL(string: &quot;BASE_URL&quot;) else {<br>      Log.assertFailure(&quot;Failed to create base url&quot;)<br>      return URLRequest(url: URL(fileURLWithPath: &quot;&quot;))<br>    }</pre><pre>    var request = URLRequest(url: url.appendingPathComponent(path))<br>    request.httpMethod = &quot;POST&quot;</pre><pre>    do {<br>      let encoder = JSONEncoder()<br>      let data = try encoder.encode(model)<br>      urlRequest.httpBody = data<br>      urlRequest.setValue(&quot;application/json&quot;,<br>                          forHTTPHeaderField: &quot;Content-Type&quot;)<br>    } catch let error {<br>      Log.assertFailure(&quot;Post request model parsing failed&quot;)<br>    }</pre><pre>    return urlRequest<br>  }<br>}</pre><p>Now, you can send models up to the server as POST requests. For example:</p><pre>let newUser = User(id: 2, name: &quot;Peter&quot;)<br>let request = PostRequest(path: &quot;/users&quot;, model: newUser)<br>Network.shared.send(request) { (result: Result&lt;Empty, Error&gt;) in<br>  print(result)<br>}</pre><h3>Status Code Errors</h3><p>One gotcha of URLSession is that it doesn’t handle status code errors. Luckily, adding logic to parse the status code is easy. And in the future, you could also handle specific status codes like unauthorized errors.</p><pre>struct StatusCodeError: Error {<br>  let code: Int<br>}</pre><pre>private func error(from response: URLResponse?) -&gt; Error? {<br>  guard let response = response as? HTTPURLResponse else {<br>    Log.assertFailure(&quot;Missing http response&quot;)<br>    return nil<br>  }</pre><pre>  let statusCode = response.statusCode</pre><pre>  if statusCode &gt;= 200 &amp;&amp; statusCode &lt;= 299 {<br>    return nil<br>  } else {<br>    Log.error(&quot;Invalid status code: \(statusCode)&quot;)<br>    return StatusCodeError(code: statusCode)<br>  }<br>}</pre><p>Next, add this check to the send function:</p><pre>if let error = error {<br>  result = .failure(error)<br>} else if let error = self.error(from: response) {<br>  result = .failure(error)<br>} else if let data = data {<br>  ...</pre><h3>Threading</h3><p>And for the last touch, let’s make this a bit more performant. URLSession already runs all networking operations on a background thread, and our model parsing for Get requests is on a background thread. But, when urlRequest() is called, it may cause some JSON parsing to run on the main thread. I recommend wrapping everything inside of send <a href="https://github.com/plivesey/Network/blob/297e6998665831901d15d1585e20a191c6f71071/Network/Network/SimpleNetwork.swift#L44">inside of an async block</a>. With that change, send won’t do <em>any</em> work on the main thread.</p><h3>Getting the Code</h3><p>If you’d prefer to just copy-paste code into your own project, you can find all the code for a full network stack (and a few examples) in <a href="https://github.com/plivesey/Network">this Github project</a>. The code for this article is shown in <a href="https://github.com/plivesey/Network/blob/master/Network/Network/SimpleNetwork.swift">SimpleNetwork.swift</a>.</p><h3>See It in Action</h3><p>I wrote a similar network stack to this in the <a href="https://apps.apple.com/us/app/navigator-meeting-assistant/id1466919451">Navigator app</a>, which helps make your meetings more productive. Of course, you can’t actually see the network stack…but hopefully, you can <em>feel</em> the elegant code through the app 😉. And, if you’re interested in working with code like this, <a href="https://aspen.team/careers/">they’re hiring</a>.</p><h3>Next time…</h3><p>This post just outlines the basics of getting a lightweight network stack up and running. With some customization, this should be enough for most apps. <a href="https://medium.com/device-blogs/adding-advanced-features-to-your-network-stack-in-swift-941ecfff8dc3">In the next post</a>, I’ve included some more advanced features that really show the power and benefit of building your own stack.</p><p><em>This project and article will need to evolve as Swift and Foundation change. If you have any suggestions, comments, improvements, bugs, please let me know in the comments or </em><a href="https://github.com/plivesey/Network/pulls"><em>submit a PR to the Github project</em></a><em>.</em></p><p><em>Thanks to Alice Avery and </em><a href="https://twitter.com/kamilah"><em>Kamilah Taylor</em></a><em> for reviewing this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f5d9ab3ea9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/device-blogs/writing-an-elegant-and-extensible-network-stack-in-swift-e2f5d9ab3ea9">Writing an Elegant and Extensible Network Stack in Swift</a> was originally published in <a href="https://medium.com/device-blogs">Device Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Many Offline Options for iOS Apps]]></title>
            <link>https://medium.com/device-blogs/the-many-offline-options-for-ios-apps-2922c9b3bff3?source=rss----75b2e3c15714---4</link>
            <guid isPermaLink="false">https://medium.com/p/2922c9b3bff3</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[offline]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[mobile-development]]></category>
            <dc:creator><![CDATA[Peter Livesey]]></dc:creator>
            <pubDate>Wed, 09 Jan 2019 04:27:18 GMT</pubDate>
            <atom:updated>2019-12-21T01:15:55.147Z</atom:updated>
            <content:encoded><![CDATA[<p>Offline mode is no longer just an extra feature you could choose to add to your app — it’s something many users expect. I’ve often seen developers force their <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/index.html">favorite offline solution</a> on a problem that could be solved in a better way.</p><p>There are many different ways of making an app work offline, each with advantages and drawbacks. There’s no magic bullet that will work every time, so it’s up to you to carefully weigh your options. Sometimes, the best solution may be a combination of several different technologies!</p><p>The main solutions available to make the app work offline are:</p><ul><li>A database, such as <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/index.html">Core Data</a> or <a href="https://realm.io/">Realm</a></li><li>A <a href="https://medium.com/@katedoesdev/normalized-vs-denormalized-databases-210e1d67927d">denormalized</a> cache, such as <a href="https://github.com/pinterest/PINCache">PINCache</a> or <a href="https://nshipster.com/nsurlcache/">NSURLCache</a></li><li>A <a href="https://medium.com/@katedoesdev/normalized-vs-denormalized-databases-210e1d67927d">normalized</a> model, cache such as <a href="https://plivesey.github.io/RocketData/">Rocket Data</a></li><li>Saving data to <a href="https://developer.apple.com/documentation/foundation/filemanager">the file system</a></li></ul><p><strong>There are many different ways to implement an offline mode, and you should always try to select the right tool for your app.</strong> But first, why should you make your app work offline?</p><h3>Why is offline important?</h3><p>First of all, <em>speed matters</em>. <a href="https://www.thinkwithgoogle.com/marketing-resources/experience-design/mobile-page-speed-load-time/">40% of users abandon pages which take more than 3 seconds to load</a>. People expect apps will be responsive and snappy. If they see a loading spinner for too long, they’ll just leave your app and open up one of the many other <a href="https://www.theguardian.com/commentisfree/2018/may/27/world-distraction-demands-new-focus">attention grabbers on their phone</a>. But, if your app works offline, it will be fast even in poor network connectivity.</p><p>Second, Business2Community estimates that <a href="https://www.digitaldoughnut.com/articles/2018/february/why-you-should-develop-an-offline-mobile-app">15% of the app usage at any time in the US is offline</a>, and in international markets, this is likely to be even higher. You users may be <a href="https://blog.superhuman.com/architecting-a-web-app-to-just-work-offline-part-1-8697f316c0eb">on a plane, in a cafe with a flaky connection, or on the subway</a>, and their internet could be coming in and out. If your app doesn’t work in these conditions, they will simply stop using your app.</p><h3>Caches vs. Databases</h3><p>When implementing an offline solution, the first step is to decide between a cache or a database. Databases can be powerful, but are overused by developers. Caches are simpler and are a better fit for many applications.</p><p>The most common database solutions are <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/index.html">Core Data</a> and <a href="https://realm.io/">Realm</a>, though many people prefer to use SQLite directly. You define models, load data from the network, and insert it into your database. Then, your view controllers listen to queries on the database and update whenever the data changes.</p><p>When implementing a cache, you load data from the cache and the network in parallel. The cached data doesn’t need to be structured and can simply be a serialized version of the data from the network. This means that loading data from the network and the cache look identical from a code perspective. There are many open source implementations of caches; <a href="https://github.com/pinterest/PINCache">PINCache</a> and <a href="https://nshipster.com/nsurlcache/">NSURLCache</a> are two common options.</p><p><strong>Databases are good if:</strong></p><ul><li>You can download all of the data for a user and store it locally without using <a href="https://www.imore.com/how-stop-facebook-making-your-iphone-run-crap">too much disk space</a>.</li><li>You can easily write logic that limits the data used on the device.</li><li>You need to be able to do simple, local searches over thousands of records.</li></ul><p><strong>Caches are good if:</strong></p><ul><li>You cannot download all the data for a user and need a simple eviction strategy.</li><li>You’ve already written logic to download data from the network and want to add in an offline mode without rewriting your application.</li><li>You want a simpler, lightweight, and flexible solution.</li></ul><p><strong>The problems with databases:</strong></p><ul><li>They are notoriously difficult to get right. You should expect to spend a decent amount of developer time dealing with crashes in this part of your application.</li><li>You need to write models and migrate them whenever something changes.</li><li>Deleting models to free up space is really difficult as it’s impossible to tell which models are currently in use by screens.</li></ul><p>Despite the downsides and overuse of databases, for some applications, it’s a great option. For example, a database would work well for a podcast player. You can download a reasonable number of upcoming episodes, and it’s easy to know when to delete models (once the user finishes an episode). Another example is a saving a game, as the user will never want to have a saved game deleted (unless they delete it manually).</p><p>On the other hand, a social media application would be much better suited with a cache. It’s impossible to download all the content for a user, and as they browse, a database would get larger and larger. In a similar vein, a news reader application would be much better with a cache. As the user browses new articles, a database wouldn’t stop growing. A cache easily stores everything you’ve recently viewed and automatically purges older articles. Additionally, you never need to migrate models or worry about <a href="https://cocoacasts.com/what-is-a-core-data-fault">data faults</a>.</p><h3>Normalized vs. Denormalized Data</h3><p>There are two main ways to store data in a cache — using normalized or denormalized data. Most application data can be visualized as a tree-like structure. It has a root model and then several child models (which then in turn could have more child models). When caching this data, you could simply store the entire tree as one entry in the cache. This will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcGf5em6tg3jUXSXB9Hahg.png" /><figcaption>A denormalized or ‘tree-like’ cache</figcaption></figure><p>This is the simplest way to use a cache. You can implement it with just a few lines of code and it’s easy to pick unique ids for objects (for instance, you could store each object by the URL you used to fetch it).</p><p>However, you’ll notice that the author object is inserted twice into the database as a nested object. This means if you update the article with id=3 with an updated author object, next time you read article with id=42, you’ll get the old author. If this type of consistency is important, you could consider ‘normalizing’ your data before you cache it. This means ripping apart the tree into submodels and caching each model under a unique id. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNsJF55KogRf34_WNWK_Bw.png" /><figcaption>A normalized cache</figcaption></figure><p>Note that this is not a database! Each entry is still a blob of unstructured data keyed by an id. This means you still won’t need migrations when models change and eviction is simple. However, implementing this system is not simple as you also need to write logic to reconstruct models and have unique ids for each submodel.</p><p>Note: because of the overhead of storing the dotted line ‘pointers’ above, this solution actually doesn’t use less space than a denormalized cache. See the ‘Additional Tips’ section for more info.</p><p>I’ve previously <a href="https://engineering.linkedin.com/blog/2016/07/rocket-data--faster-model-management-for-ios">written about using this strategy for the LinkedIn App</a>, and the <a href="https://github.com/plivesey/RocketData">code that powers consistency amongst models is open-source</a>. Using this solution, adding offline behavior was easy for new pages, and we never had to migrate models or clean up large databases.</p><h3>Downloading Data from a Server</h3><p>There are a few options for retrieving data from the network and the cache or database.</p><p>The simplest is to always retrieve data from the cache and network in parallel. If the cache returns first, call your completion block with the cached data. Then, once the network finishes, call the completion block with the new data. This allows you to contain most of the caching logic in the network layer and all the view controllers need to do is display the data.</p><p>However, this approach will sometimes call the completion block twice. For some apps, this may be problematic, so you could consider only using the cached data if the network is slow. You only display the cached data if the network fails or takes too long to load. I’d recommend setting the timeout for this to be short. Remember that when offline, requests will often timeout after a minute instead of erroring immediately.</p><p>Another solution is to place your cache or database between your view controllers and network. In this ‘reactive’ model, you immediately retrieve models from the database and listen for changes. Once the network request finishes, it edits the database and the view controller automatically updates with the changes. This approach has been <a href="https://www.netguru.co/blog/how-to-design-offline-first-approach-in-mobile-app">well-documented</a>. It’s a simple mental model, but listening to model changes in all view controllers is <a href="https://github.com/realm/realm-cocoa/issues/4818">sometimes not trivial</a> and leads to <a href="https://medium.com/inspace-labs-blog/how-to-observe-changes-on-single-instance-of-nsmanagedobject-f64532f36ef4">a lot of boilerplate code</a>.</p><p>Finally, you can use a database sync solution such as <a href="https://realm.io/products/realm-platform">Realm Platform</a> or <a href="https://firebase.google.com/">Firebase</a>. With these platforms, you host a version of the database on your server and changes are automatically synced to clients in a data-efficient way. These solutions implement a lot of complexity, but this complexity is hidden in a black box and has nontrivial requirements on how you structure your server.</p><h3>Uploading Data</h3><p>When users change data in an application, it’s difficult to decide how this should work in low network connectivity. The simplest way is to show a spinner and wait for the request to finish. You can block the UI and if necessary, alert the user that something failed with a banner or alert. However, this is isn’t the best user experience. I still cannot believe that iMessage won’t allow me to send messages when offline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*UMrvIZEMAsjyEgBCcu5xuA.jpeg" /><figcaption>iMessage doesn’t work offline? What is this? 2014?!</figcaption></figure><p>A common solution to this problem is to create a queue for offline tasks. If a request fails because of low connectivity, add it to a disk-backed queue and try again when you are connected to the internet. While this sounds simple in theory, in practice, there are a lot of edge cases you need to consider:</p><ol><li>How many times should you retry a request?</li><li>Is the ordering of requests important?</li><li>If a request finally fails after a number of retries, how do I inform the user?</li><li>How do I let the user know that a request is pending and hasn’t yet synced?</li></ol><p>On top of all this, you need to revert the data if an upload fails. Consider the following flow:</p><ol><li>The user likes something on their phone which is <em>offline</em>.</li><li>The user likes the same thing on their laptop which is <em>online</em>.</li><li>The phone connects to the internet, and downloads new data for this item (which says it is liked).</li><li>Next, uploading this like on the phone fails for some reason.</li><li>The phone reverts the item to no longer be liked.</li></ol><p>Notice how the phone ends up in the wrong state! Even worse, since the phone doesn’t know it’s not in the right state, it may not refresh this from the network. When reverting data, you can’t simply take the opposite of an action. You need to revert to the last thing the server told you was correct. This means you now need to store both your current state and the last seen server state.</p><p>These problems are still solvable. When I was at <a href="https://superhuman.com/">Superhuman</a>, we built an architecture we called a ‘modifier queue’ that solved all of these edge cases. You can read more details on this <a href="https://blog.superhuman.com/">on the Superhuman blog</a>.</p><p>Likely for your app, you don’t need to go as far as implementing a modifier queue. Uploading data is difficult, and you should think through which use cases you care most about and concentrate on those being great experiences.</p><h3>Consistency</h3><p>Once you’ve edited your cache or database locally, you may need to update multiple screens in the app. This is a deep topic that is way beyond the scope of this post, but here are a few techniques to consider:</p><ul><li><strong>Listening to Database Changes<br></strong>Most databases offer the ability to listen to models changing. If you’re using a database instead of a cache, this is likely the simplest solution.</li><li><strong>Delegation<br></strong>If a change only affects a couple of view controllers in your app that have a relationship, you can simply use a delegate to propagate the change. Though you can only use this if the change doesn’t appear elsewhere, this is a very simple solution and you shouldn’t overlook it if it just works.</li><li><strong>An Event Bus<br></strong>One of the simplest ways to implement changes to a cache is to use an event bus system to notify all listeners of changes. You simply listen to changes to a certain id and if it changes, reload data from the cache and refresh the view. NSNotificationCenter is the first party solution, but I’d recommend looking at some open source projects that offer a better API as well as typesafe notifications. <a href="https://github.com/100mango/SwiftNotificationCenter">SwiftNotificationCenter</a> and <a href="https://github.com/cesarferreira/SwiftEventBus">SwiftEventBus</a> are two popular examples.</li><li><strong>Rocket Data<br></strong><a href="https://github.com/plivesey/RocketData">Rocket Data</a> manages the consistency for immutable models and is specifically designed to work well with a cache. It simply listens to changes on certain ids and notifies you when a model has changed. It’s a more powerful solution than the event bus and <a href="https://academy.realm.io/posts/slug-keith-smiley-embrace-immutability/">allows you to use immutable models</a>, but also requires more work to set it up. For more information, see <a href="https://academy.realm.io/posts/slug-peter-livesey-managing-consistency-immutable-models/">my talk on Rocket Data</a> or <a href="https://plivesey.github.io/RocketData/">the docs</a>.</li></ul><h3>Combining Techniques</h3><p>I recently added an offline mode to my <a href="https://itunes.apple.com/us/app/chess-tactics-and-lessons/id531275673?mt=8">Chess Tactics App</a>. I had three use cases for offline usage, each with slightly different requirements:</p><ul><li>Users should be able to view all pages in the app offline if they’ve visited them recently.</li><li>Users should be able to explicitly save puzzles to view offline. These should never be evicted.</li><li>The main feature of the app presents a random puzzle to the user curated for their skill level. This should work offline.</li></ul><p>Instead of picking one architecture and trying to fit all of these use cases to it, I decided to pick three different offline techniques!</p><p>For viewing arbitrary pages, I simply added a <a href="https://github.com/pinterest/PINCache">key-value store cache</a> keyed off the URL for the request. I chose a denormalized cache since I didn’t have many submodels in my requests, and submodel consistency isn’t important to my application. Even though I had already coded the entire app, adding this was trivial and only took a couple of hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*ahtjtGTer9WxJlp3AIogIQ.jpeg" /><figcaption>Playing puzzles works offline! The rating change is added to a queue and the requests are sent when the user comes back online.</figcaption></figure><p>For saving puzzles, I used a structured database. I never wanted these evicted and there was no chance that the user could save too much data since an individual puzzle is only a few KB. A structured database also allows the flexibility to sort or filter these puzzles in the future.</p><p>For presenting a random puzzle to the user, I also used a database, but instead of using a structured database, I simply used an NSData blob to store the JSON. In the background, the app downloads about 200 puzzles and stores them. If the user is offline, the app selects one randomly (an operation that is difficult with a cache), presents it to the user, and then deletes it. Using a database fit my needs as I could easily control its size. Storing the data as a blob instead of using separate fields allowed me to simplify my code and avoid any additional parsing logic. Contrary to popular belief, storing data as blobs is very fast with a database <a href="https://www.sqlite.org/fasterthanfs.html">as long as the blobs are small</a>.</p><p>When selecting a random puzzle offline, my view controller never used database models directly. Instead, I parsed the data blob into an in memory model before passing it to the view controller. This way, my view controller was completely isolated from any disk storage logic, and I could safely delete these models at any time.</p><p>For uploading data, I implemented a simple queue to upload user rating changes. Since the app is read-heavy, I decided it wasn’t worth it to implement other POST requests. The app simply shows a message saying: ‘your rating will update when you are online.’</p><p>The key point here: you shouldn’t force every feature to use the same offline solution. By combining different techniques, you can provide a better user experience and reduce development time.</p><h3>Conclusion</h3><p>If nothing else, I hope you remember that there are many different solutions for making an app work offline. Don’t just start banging your head against a Core Data implementation immediately because it’s what you’re familiar with; think hard about the problem you’re trying to solve before selecting the best solution.</p><p>For many apps, a cache is a better choice, because it’s a simpler solution. It offers an easy method for eviction, it doesn’t require model migrations, and <a href="https://stackoverflow.com/search?q=core+data+crash">doesn’t crash all the time</a>.</p><p>Regardless of your chosen technology, you also need to consider how you are going to upload changes and keep your app consistent as part of your offline strategy. And finally, you shouldn’t box yourself into just one technology. Often, a combination of different techniques will be the best solution.</p><h3>Additional Tips</h3><p><strong>Where should you save data?</strong></p><p>iOS actually provides a cache directory for storing cache data. However, this directory is <a href="https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html">cleared if the device is running low on space</a>. This is a great thing if it’s actually a cache, but not if you’re relying on this data for basic functionality. You can also put files in the tmp folder for even shorter lived files.</p><p><strong>Offline Detection on iOS is very Flaky</strong></p><p>Apple offers a <a href="https://developer.apple.com/documentation/systemconfiguration/scnetworkreachability-g7d">reachability API</a> that notifies you when connection to the internet changes in some way. However, this API is flaky and you shouldn’t rely on it for infrastructure logic. Internally, it never actually makes network requests. It just tells you when the hardware <em>could</em> connect to the internet. You can use this API for UI to show to the user, but you should never avoid sending a request because of this API — the only way to know if you’re actually able to reach your server is to try the request. Jared Sinclair recently <a href="http://blog.jaredsinclair.com/post/179083065595/til-boy-have-i-been-misusing">wrote a good article on this</a>.</p><p><strong>Normalized Caches Don’t Use Less Data</strong></p><p>As I mentioned earlier, normalized caches don’t necessarily use less data than denormalized caches. Though they don’t duplicate models, there is overhead to store data separately. Consider the following trivial example:</p><pre>// Denormalized data<br>{ id: &#39;parent&#39;, child: { id: &#39;child&#39; }}</pre><pre>// Normalized data<br>{ id: &#39;parent&#39;, child:<strong> &#39;child&#39;</strong> }<br>{ id: <strong>&#39;child&#39;</strong> }</pre><p>Notice how in the second example, the id of the child model is duplicated meaning that the total bytes used by the normalized data in this instance is actually higher. This seems small, but if you have a lot of small, nested models, it really adds up quickly. When working on the LinkedIn app, we found that normalized data took up about 5–10% more space than denormalized data. Because of this, we decided to send denormalized data over the network where size matters.</p><p>Of course, this is dependent on your specific dataset. There’s a tradeoff here, so measure before you decide!</p><p><strong>The Fastest Cache is SQLite!?</strong></p><p>Ironically, the fastest cache I’ve found that’s readily available for iOS development is actually SQLite. You can simply create a model with three fields: id, data, and timestamp. After creating an index on id, lookup and storage is faster than the NSFileManager solution used by many open source solutions. As far as I know, there’s no open source library that implements this API and eviction logic, but if you’re interested in creating one, let me know. I’d be interested in contributing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2922c9b3bff3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/device-blogs/the-many-offline-options-for-ios-apps-2922c9b3bff3">The Many Offline Options for iOS Apps</a> was originally published in <a href="https://medium.com/device-blogs">Device Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Assertions in Production]]></title>
            <link>https://medium.com/device-blogs/assertions-in-production-e587fef5bfbc?source=rss----75b2e3c15714---4</link>
            <guid isPermaLink="false">https://medium.com/p/e587fef5bfbc</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Peter Livesey]]></dc:creator>
            <pubDate>Sun, 11 Nov 2018 03:37:17 GMT</pubDate>
            <atom:updated>2018-11-14T15:36:12.206Z</atom:updated>
            <content:encoded><![CDATA[<p>Backend engineers know exactly what’s going on with their services. They know their QPS, memory footprint, error rate, and CPU utilization in real time. They even get paged automatically if there’s a critical error so they can respond quickly. Unfortunately, iOS engineers usually only have crash reporting and <em>maybe</em> some product metrics. Usually, we learn about bugs when a user reports it, or worse, when a user posts a bad review. <em>We can do better.</em></p><h3>Reporting Assertions</h3><p>Assertions are conditional checks that ensure that your code is working as expected. Likely, you already have a few in your codebase. They check conditions which should never fail, and if they do, it’s signifies a <em>critical bug</em> in your code. However, assertions are removed in production and have no effect in the real world. On every project I’ve worked on, I’ve added a custom Log type which makes assertions report the error in production. Most crash reporting frameworks have the ability to report non-fatal errors, so implementing this is trivial. Here’s an example using <a href="https://firebase.google.com/docs/crashlytics/">Crashlytics</a>:</p><pre><strong>enum</strong> Log {<br>    <strong>static</strong> <strong>func</strong> assert(<strong>_</strong> condition: <strong>@autoclosure</strong> () -&gt; Bool, <strong>_</strong> message: <strong>@autoclosure</strong> () -&gt; String, file: StaticString = <strong>#file</strong>, line: UInt = <strong>#line</strong>) {<br>    #if DEBUG<br>        Swift.assert(condition(), message(), file: file, line: line)<br>    #else<br>        <strong>if</strong> !condition() {<br>            <strong>let</strong> domain = message()<br>            <strong>let</strong> error = NSError(domain: domain, code: domain.hashValue, userInfo: <strong>nil</strong>)<br>            Crashlytics.sharedInstance().recordError(error)<br>        }<br>    #endif<br>}</pre><pre><strong>    static</strong> <strong>func</strong> assertFailure(<strong>_</strong> message: <strong>@autoclosure</strong> () -&gt; String, file: StaticString = <strong>#file</strong>, line: UInt = <strong>#line</strong>) {<br>        Log.assert(<strong>false</strong>, message, file: file, line: line)<br>    }<br>}</pre><p>In DEBUG, the assert works as it normally does and crashes your app. But in RELEASE builds, it creates an error and reports it to Crashlytics. This will show up like a normal crash but with a non-fatal label. It even includes a stack trace!</p><p>This has been invaluable to responding quickly to bugs. A new non-fatal exception tells me that my code is behaving in an unexpected way. With a stack trace, iOS versions, and the frequency of the problem, I can start trying to reproduce the problem and fix it. Now, I’m responding to bugs <em>before</em> users report them or write bad reviews.</p><h3>Property Tests</h3><p>I’d argue that this use of assertions is a form of <a href="https://techbeacon.com/how-make-your-code-bulletproof-property-testing">property testing</a>. To write a property test:</p><ol><li>You define certain properties which must hold for a certain function.</li><li>Then, you feed the function random input.</li><li>If the properties hold, then the test passes.</li></ol><p>With assertions, instead of writing these tests explicitly, your users generate the input! Your assertions define the ‘properties’ that should always be true. Though your users don’t generate purely random input, the input is often diverse and unexpected. The best part is — these tests don’t require writing any real tests!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*KYLfEYet5XyMkG5NECfUmg.jpeg" /><figcaption>Of course, relying exclusively on testing in this manner isn’t a good idea. But, it does give you some additional confidence that your app is running correctly. <a href="https://medium.com/@aeh.herman/first-steps-in-frontend-testing-with-tdd-bdd-part-ii-a73f529d5914">Source</a></figcaption></figure><p>If you’re interested in property testing, check out <a href="https://github.com/linkedin/LayoutTest-iOS">LayoutTest</a> — a framework which enables you to easily write property tests for your views. The library generates random JSON data and inflates your views with it. Then, you assert properties on your view (such as spacing is correct and no views are overlapping).</p><h3>When to Assert</h3><p>Assertions are underused in most iOS apps and frameworks. Incorrect assumptions about how a function will be used are a common cause of subtle bugs . My general rule is:</p><blockquote>If there is no else statement, there should be an assertion.</blockquote><p>For example:</p><pre>guard let x = x else {<br>    return<br>}</pre><p>What if x is nil? Do we need to show an error to the user? Will some infrastructure silently fail? Often, x should just never be nil. In this case, I’d add an assertion to the else statement:</p><pre>guard let x = x else {<br>    Log.assertFailure(&quot;x is unexpectedly nil&quot;)<br>    return<br>}</pre><p>This is easy to add and also helps document assumptions in the code. Here, my assumption is clear: x should never be nil.</p><p>I also add assertions for:</p><ul><li>Verifying function parameters are correct</li><li>Reading from dictionaries with ‘known keys’ such as NSNotification userInfo</li><li>Log.assert(Thread.isMainThread, &quot;Not on the main thread!&quot;)</li><li>Opening a critical database or file fails</li></ul><h3>Shouldn’t I Let Assertions Crash in Production?</h3><p>I know some of you are thinking: ‘when you hit an assertion, your program is in an unknown state, so it’s better to crash than continue.’ In theory, this may be true, but in practice, I’ve never found it to be valid. It’s often trivial to provide a degraded experience to the user. An empty screen is better than a crash. And since you’ll be able to react quickly to the problem, a fix will be out soon. If you are developing a security framework or banking application, crashing is maybe acceptable. But for most applications, it’s unnecessary to burden your users with your mistakes.</p><h3>But, I Don’t Hit Assertions When Developing</h3><p>You may not hit many assertions when you are developing, but you’d be surprised at what states your users manage to get your app into. You probably don’t test your app on every device, in every network condition, with every operating system, and with every account. I have seen many assertions fire in production which I’ve never seen before in development.</p><p>Are you using a different system to track errors? Do you have other ideas for improving assertions? Let me know in the comments!</p><p><em>Thanks to Sanket Firodiya, Alice Avery, Kamilah Taylor, Melissa Huang, Joe Fabisevich, and Kyle Sherman for helping review this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e587fef5bfbc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/device-blogs/assertions-in-production-e587fef5bfbc">Assertions in Production</a> was originally published in <a href="https://medium.com/device-blogs">Device Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Steps to a Better Onboarding Experience]]></title>
            <link>https://medium.com/device-blogs/5-steps-to-a-better-onboarding-experience-11945f0b8abf?source=rss----75b2e3c15714---4</link>
            <guid isPermaLink="false">https://medium.com/p/11945f0b8abf</guid>
            <category><![CDATA[onboarding]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[chess]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Peter Livesey]]></dc:creator>
            <pubDate>Mon, 17 Sep 2018 19:30:11 GMT</pubDate>
            <atom:updated>2018-09-21T16:36:06.376Z</atom:updated>
            <content:encoded><![CDATA[<p>Likely, your app’s onboarding experience isn’t very good. This isn’t because your product isn’t well designed or easy to learn; it’s because building successful onboarding experiences is just <em>hard</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*bu6kKL8eOTgPBetyIsFuhg.jpeg" /><figcaption>todayfm.com</figcaption></figure><p>A couple of months ago, my <a href="https://itunes.apple.com/us/app/chess-tactics-and-lessons/id531275673">chess puzzle app</a> was struggling to retain new users. I loved the app, and many of my users did too, but, most people who downloaded the app wouldn’t use it more than once. So, I decided to build an onboarding experience for all the lost users.</p><p>Today’s users are <a href="https://uxplanet.org/why-todays-app-users-are-the-most-complicated-ever-4bd18186147">more discerning than ever</a>, <a href="https://www.statista.com/statistics/268251/number-of-apps-in-the-itunes-app-store-since-2008/">have more options</a>, and have <a href="https://in.reuters.com/article/apps-attention-span/when-it-comes-to-apps-consumers-have-shorter-attention-spans-idINDEE97J0DU20130820">shorter attention spans</a>. When you look at your product, you may see a useful, beautiful, fun app which is great at solving a specific problem or need. But when new users see your product, they see a <a href="https://justuxdesign.com/blog/the-paradox-of-choice-more-isn-t-always-better">menu with too many options</a>, a login screen trying to steal their email address, and a learning hurdle they need to overcome.</p><p>I followed five steps which got me to an onboarding experience I was proud of:</p><ol><li>Dissect your current onboarding</li><li>Make your users successful ASAP</li><li>Bucket your users</li><li>Test it on real users</li><li>Measure your success</li></ol><h3><strong>1. Tear it apart</strong></h3><p>It’s hard to critique your own work, but it’s a valuable skill to foster. I was inspired to take this step seriously by <a href="https://www.useronboard.com/">useronboard.com</a>. The site has done incredible teardowns of many famous products and does a fantastic job showing what works and doesn’t work when onboarding new users. I’d highly recommend going through several of their slideshows before taking a look at your own product.</p><p>So, here is my teardown of my old app with all its flaws. I hope you find it brutal enough.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2Fzk3lapbW0AoFXd&amp;url=https%3A%2F%2Fwww.slideshare.net%2FPeterLivesey1%2Fchess-tactics-lessons-onboarding-analysis&amp;image=https%3A%2F%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2Fchesstacticsonboarding-180905173558-thumbnail-4.jpg%3Fcb%3D1536169096&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/36fde73132b77678dcea7fa5b1f62ba6/href">https://medium.com/media/36fde73132b77678dcea7fa5b1f62ba6/href</a></iframe><p>There’s obviously a lot to improve, but the top things I decided to fix were:</p><ol><li>Persuade the user the app is worth their time before asking them to sign up.</li><li>Set up each user for success, not failure.</li><li>Minimize choice when users first use the product.</li></ol><h3><strong>2. </strong>Make your users successful ASAP</h3><p>Great products aren’t just powerful; they make people <em>feel</em> powerful. Your product should <a href="https://medium.com/building-winning-products/kathy-sierra-on-designing-for-badass-ba92cd5fad96">transform your user into a better version of themselves</a>. This could be making them more productive, more informed, or simply happier. You need to identify the <strong>earliest moment that people feel this emotion</strong>.</p><p>For us, this action was completing a difficult puzzle correctly. Chess is a hard game, so this is no easy feat. But when users overcome this challenge, they realize they’ve become something new — a smarter chess player. This transformation will persuade them to keep using the app.</p><p>Currently, the app requires users to sign in before even attempting a puzzle. Instead of this, I rewrote how login worked to allow people to play puzzles without signing up. I <strong>only ask them to sign up after they’ve successfully completed a puzzle</strong>. But, the order of these actions is only half the problem. As I said, chess is a difficult game, and many users aren’t yet capable of completing a difficult puzzle. If the app gave them a difficult puzzle immediately, they’d be set up to fail.</p><h3><strong>3. Bucket users</strong></h3><p>When an experienced player comes to the app, they want to be challenged. But, if the first puzzle the app gives users is too difficult, beginners will fail. So, I had to design different experiences for beginners and experts. This is the first screen for a fresh install:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*8-5VeGkUMadCNMvP2D1lVg.png" /><figcaption>First launch screen</figcaption></figure><p>A couple of things to note:</p><ol><li>This screen has only three options so the user won’t be overwhelmed for choice.</li><li>Users are often nervous about picking wrong and then having to restart. The help text at the bottom should help these users realize that this decision won’t ruin their experience if they pick slightly wrong.</li></ol><p>Likely, your user cohorts will be different. If you’re a music discovery app, you might bucket users into those who are looking for specific music and users who want to explore new music. For a reading app, you may split your users into fiction readers, nonfiction readers or other genres. Just make sure you don’t make the mistake that <a href="https://support.apple.com/en-us/HT204842">Apple Music</a> and many other apps make which overload their users with options. <strong>People are way more willing to enhance their profile <em>after</em> they see value than before.</strong> You should bucket them just enough to get them to that key experience you’ve identified.</p><p>If a user is a beginner, they start with some interactive lessons which teach them how to solve chess puzzles. If the user is advanced, they go straight into tough and interesting puzzles.</p><h3><strong>4. User Testing</strong></h3><p>Once you’ve built a first version of your onboarding, you need to test it on some real people! You’ll be shocked at how difficult people find things which you think are easy. The best way to do this testing is in person. You won’t understand how people are using your app unless you actually watch them. Find some friends who haven’t used the app, sit down with them and ask them to start using the app. Likely, they will quickly ask you questions on how things work or what they should be doing. Resist the urge to help them! Instead, simply reply with more questions like:</p><p>“What would you do if I weren’t here?”</p><p>“Do you see a way of answering that with the product?”</p><p>Every time they ask you a question, it shows a weakness in your onboarding flow. New users have no loyalty and will quickly revert to using other apps at the first sign of trouble. Candy crush is just a few taps away and you only have <a href="http://fortune.com/2016/05/19/app-economy/">one chance to convert each person</a>. On one of the user tests I did, I wrote down twenty-nine places the user could have dropped out! Each problem was just a small fix such as writing clearer copy or adding a tooltip.</p><h3><strong>5. Measure success</strong></h3><p>When you release your new experience, you’ll want to see how much better you’re app is doing. You should identify a few metrics which you expect to improve after the release. For my app, I wanted to improve 1-day and 7-day churn as well as have more users attempt at least one puzzle. You don’t need to overdo it here and track every user action as they onboard. Just track a few key flows and try to find where users drop off.</p><p>We’ve only just released the new update, so I don’t have much data yet. Early results suggest that <strong>day 1 retention has approximately doubled</strong>. I’ll update this post once we have more to share!</p><p><em>Update:</em> It’s been a little over two weeks since we released the new version and day 1 retention has remained bullish (increasing by about 2.5x). However, day 7 retention has only increased by about 50%. This is still a great improvement, but I think I can do even better. Since most of my work concentrated on the first few days, this isn’t that surprising. Next, I should look at keeping the user engaged a week or more after they’ve used the product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*FxDGcCN-VdZXF5uhvZ--eA.png" /><figcaption>Success! The sooner users get here, the better.</figcaption></figure><h3><strong>Try it for yourself</strong></h3><p>If you’re looking for ideas, want to learn something new, or just have some fun, check out what we’ve done. You can download the <a href="https://itunes.apple.com/us/app/chess-tactics-and-lessons/id531275673">new Chess Tactics &amp; Lessons on the App Store</a>, and let us know what you think of the onboarding process in the comments.</p><p><em>Thanks to Alice Avery, Nick Snyder, Islam Sharabash, Judy Logan, Ryan Blunden, and Joe Kramer for your help on this post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11945f0b8abf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/device-blogs/5-steps-to-a-better-onboarding-experience-11945f0b8abf">5 Steps to a Better Onboarding Experience</a> was originally published in <a href="https://medium.com/device-blogs">Device Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>