Debugging Network Traffic With Proxyman

Disclaimer: This post is not sponsored by Proxyman, nor am I affiliated with Proxyman in any way. I pay for my license myself, and this post is simply written as a guide to learning more about a tool that I find very important in the iOS Developer toolbox.

Networking is an essential part of modern iOS applications. Most apps I’ve worked have some kind of networking component. Sometimes the networking layer involves user authentication, token refresh flows, and more. Other times, I’ll simply need to hit one or two endpoints to fetch new data or configuration files for my app.

When this all works well, everything is great. But when I notice that things don’t work quite as expected, it’s time to start digging in and debug my network calls. The most simple method would be to convert the data that I’ve fetched from the server to a String and printing it. However, a large response will be hard to read in Xcode’s console so you might have to paste it elsewhere, like in a JSON validator.

When the response you receive is wrong, or not quite what you expected, you’ll want to take a look at the data you’ve sent to the server to make sure you’re not sending it bad data. Doing this isn’t always trivial. Especially when you’re dealing with setting HTTP headers and/or multipart form requests.

In this post, I will show you how you can gain insight into the requests that your app sends to the server as well as see the responses that the server sends to your app. To do this, we’ll use he app Proxyman.

💡 Tip: I’ve written a similar post to this one about Charles Proxy that you can read here. Over time I’ve come to prefer Proxyman for debugging because it’s a nicer app and it’s just a bit easier to set up.

Installing and configuring Proxyman

To use Proxyman, you must first download and install it. You can do this right here on their website. The download for Proxyman is free, and the free version of the app is perfectly usable to explore and learn about debugging your app through a proxy. However, Proxyman isn’t a free app and if you want to use all its features you’ll need to purchase a license. Luckily, a single license is valid forever and entitles you to a year of free updates. After that you can continue the last version that became available during the year, or buy a new license for another year of updates.

Once you’ve downloaded Proxyman, install it by opening the dmg and dragging the app to your Applications folder.

When you first launch Proxyman, it will prompt you for some setup steps and eventually Proxyman will want to install a helper tool. You can safely accept all of Proxyman’s defaults and install the helper tool.

Proxyman helper tool prompt

After setting everything up, you should immediately see network traffic appear in Proxyman’s main window. This is all of the traffic that your Mac is sending and receiving in real-time. This means that you can see any app or website’s network traffic in Proxyman.

When you click on one of the requests, you can see some details about the request. Like for example the request headers, body, and more. You can also see the response for a given request.

There is a caveat though; if the request is performed over HTTPS you won’t see anything just yet.

In the screenshot below, I’ve selected all traffic made by the Proxyman app in the left hand sidebar, and I’ve selected one of the requests in the main section to see more details. Because the request is made using HTTPS, I need to explicitly enable SSL proxying for either a specific host, or all requests made by, in this case, the Proxyman app. Once enabled, re-executing these requests would allow me to inspect their contents.

Proxyman main window

When you first allow SSL proxying for either a domain or an app, you will be prompted to install the Proxyman root certificate. Proxyman can do this automatically for you which is quite convenient. You will be prompted for your admin password so that Proxyman can update your settings and allow SSL proxying.

After enabling SSL proxying, you can select any request and repeat it to make sure that you can now inspect your request and the server’s response. Note that repeating a request isn’t always a valid thing to do so the server you’re hitting might give you an error response; this isn’t something you did wrong with your setup, if you can see the error code everything is working as intended.

Repeat Request in Proxyman

With Proxyman set up, let’s see how we can use it for our apps.

Using Proxyman with the simulator

In order to see the iOS simulator’s traffic appear in Proxyman, you’ll need to install the Proxyman certificates in the simulator. You can do this by selecting Certificates -> Install Certificate on iOS -> Simulators.... This will automatically add the needed certificates to your active iOS simulators so make sure the simulator you want to debug with is active.

Using Proxyman with the simulator

After installing the certificate, you need to reboot your simulator. Once you’ve done this, you can re-run your app and you should start seeing your simulator’s network traffic appear. If you haven’t enabled SSL proxying for the hosts you’re hitting yet, you might have to do this first as you’ve seen earlier.

Inspecting your networking traffic is done in the bottom section of the Proxyman window. On the left side you can see the request you’re sending to the server. You can inspect headers, the request body, query parameters, and anything else you might need.

On the right side of the window you can see the server’s response body and headers.

Proxyman request and response

Being able to have real-time detailed insights into the exact request and responses you’re dealing with is extremely convenient. What’s even more convenient is that you can use Proxyman on a physical device too, allowing you to connect your device to Proxyman on your mac whenever you need to quickly check what your app is doing; even for production builds!

Using Proxyman with a real device

To run Proxyman on a real device, there are a couple of things you’ll need to do. Luckily, Proxyman provides really good instructions in the Mac app.

Start by selecting Certificate -> Install Certificate on iOS -> Physical Devices....

Menu option for proxyman on real device

This will open a window with instructions that you should follow to set up Proxyman for your device.

Proxyman on device instructions

You only need to go through all of these steps once. When you’ve set up your device, all you need to do to start a debugging session is to launch Proxyman on your Mac, connect your iOS device to the network that your Mac is on, and set up the proxy settings for your device in your WiFi settings.

Sharing Proxyman logs with others

One of the main selling points of using a proxy to debug networking isn’t that it’s convenient for developers to validate the request and responses they’re creating and receiving in their apps. In my opinion one of the key selling points of Proxyman is the fact that anybody can install it to capture network traffic.

This means that your QA team can run their device through Proxyman to capture an app’s networking traffic, and include a log of network calls made by the app along with a bug report. This is extremely valuable because it makes troubleshooting network related issues infinitely easier. Having a detailed overview of network calls is so much better than “I just keep getting an unknown error”.

Furthermore, when you’re sure that you’re sending your backend the right thing but the response you’re getting is malformed, or not what you expected, you can easily get Proxyman to export a cURL command that you can send to your backend engineers to help them figure out what’s wrong.

To export a collection of requests you can select them in the main window and right click. Then select Export to see the various export options that are available. You’ll typically want to export as Proxyman Log but if the receiver of your log doesn’t have Proxyman, Charles, Postman, or another format might be more useful.

Export batch of requests

If you just want to export a cURL for a single request you can select the request you want a cURL for, right click, and select Copy cURL. This will get you a cURL request that anybody can run to repeat the request that you’re debugging.

Copy curl menu option

Sending a log or a cURL along with any bug report you have is a really good practice in my opinion. Not only does it improve the quality of your reports, it also makes the lives of your fellow engineers, and backend engineers a lot easier because they’ll have much better insights into what the app is doing with regards to networking.

In addition to capturing iOS device traffic through the Mac app, you can also capture traffic directly on your iOS device with the Proxyman for iOS app. The app can be downloaded through the App Store, and it allows you to quickly start a debugging session right on your iOS device. This can be incredibly useful when you’re not near a Mac but see some weird behavior in your app that you want to explore later. I don’t use the iOS app a lot, but I wanted to mention it anyway.

In summary

In today's tip, you learned how you can use Proxyman to inspect and debug your app’s networking traffic. Being able to debug network calls is an essential skill in the toolbox of any iOS developer in my opinion. Or more broadly speaking, anybody that’s involved in the process of building and testing apps should know how to run an app through a proxy like Proxyman to gain much better insights into an app’s networking traffic, and to build much better bug reports.

This post is merely an introduction to Proxyman, it can do a lot more than just show you request / response pairs. For example, it also allows you to throttle network speeds for specific hosts, and it even allows you to replace requests and responses with local files so you can override what your app sends and/or receives when needed for debugging.

For now, I wish you happy debugging sessions and don't hesitate to shoot me a message on Twitter if you have any questions about debugging your network calls.

The difference between checked and unsafe continuations in Swift

When you’re writing a conversion layer to transform your callback based code into code that supports async/await in Swift, you’ll typically find yourself using continuations. A continuation is a closure that you can call with the result of your asynchronous work. You have the option to pass it the output of your work, an object that conforms to Error, or you can pass it a Result.

In this post, I won’t go in-depth on showing you how to convert your callback based code to async/await (you can refer to this post if you’re interested in learning more). Instead, I’d like to explain the difference between a checked and unsafe continuation in this short post.

If you’ve worked with continuations before, you may have noticed that there are four methods that you can use to create a continuation:

  • withCheckedThrowingContinuation
  • withCheckedContinuation
  • withUnsafeThrowingContinuation
  • withUnsafeContinuation

The main thing that should stand out here is that you have the option of creating a “checked” continuation or an “unsafe” continuation. Your gut might tell you to always use the checked version because the unsafe one sounds... well... unsafe.

To figure out whether this is correct, let’s take a look at what we get with a checked continuation first.

Understanding what a checked continuation does

A checked continuation in Swift is a continuation closure that you can call with the outcome of a traditional asynchronous function that doesn’t yet use async/await, typically one with a callback closure.

This might look a bit as follows:

func validToken(_ completion: @escaping (Result<Token, Error>) -> Void) {
  // eventually calls the completion closure
}

func validTokenFromCompletion() async throws -> Token {
    return try await withCheckedThrowingContinuation { continuation in
        validToken { result in
            continuation.resume(with: result)
        }
    }
}

The code above is a very simple example of bridging the traditional validToken method into the async/await world with a continuation.

There are a couple of rules for using a continuation that you need to keep in mind:

  • You should only call the continuation’s resume once. No more, no less. Calling the resume function twice is a developer error and can lead to undefined behavior.
  • You’re responsible for retaining the continuation and calling resume on it to continue your code. Not resuming your continuation means that withCheckedThrowingContinuation will never throw an error or return a value. In other words, your code will be await-ing forever.

If you fail to do either of the two points above, that’s a developer mistake and you should fix that. Luckily, a checked continuation performs some checks to ensure that:

  • You only call resume once
  • The continuation passed to you is retained in your closure

If either of these checks fail, your app will crash with a descriptive error message to tell you what’s wrong.

Of course, there’s some overhead in performing these checks (although this overhead isn’t enormous). To get rid of this overhead, we can make use of an unsafe continuation.

Is it important that you get rid of this overhead? No, in by far the most situations I highly doubt that the overhead of checked continuations is noticeable in your apps. That said, if you do find a reason to get rid of your checked continuation in favor of an unsafe one, it’s important that you understand what an unsafe continuation does exactly.

Understanding what an unsafe continuation does

In short, an unsafe continuation works in the exact same way as a checked one, with the same rules, except it doesn’t check that you adhere to the rules. This means that mistakes will not be caught early, and you won’t get a clear description of what’s wrong in your crash log.

Instead, an unsafe closure just runs and it might crash or perform other undefined behavior when you break the rules.

That’s really all there is to it for an unsafe continuation, it doesn’t add any functionality, it simply removes all correctness checks that a checked continuation does.

Choosing between a checked and an unsafe continuation

The Swift team originally suggested that we always make use of checked continuations during development, at least until we’ve verified the correctness of our implementation. Once we know our code is correct and our checked continuation doesn’t throw up any warnings at runtime, it’s safe (enough) to switch to an unsafe continuation if you’d like.

Personally, I prefer to use checked continuations even when I know my implementation is correct. This allows me to continue working on my code, and to make changes, without having to remember to switch back and forth between checked and unsafe continuations. Members of the Swift team have, eventually, come forward stating that they thing using unsafe continuation is a mistake for most developers. We should be using checked continuations unless we're absolutely certain that switching to unsafe makes sense. For example, when checked continuations are actually giving you performance problems (they probably won't in your app).

Of course, there is some overhead involved with checked continuations and if you feel like you might benefit from using an unsafe continuation, you should always profile this first and make sure that this switch is actually providing you with a performance benefit. Making your code less safe based on assumptions is never a great idea. Personally, I have yet to find a reason to favor an unsafe continuation over a checked one.

Migrating callback based code to Swift Concurrency with continuations

Swift's async/await feature significantly enhances the readability of asynchronous code for iOS 13 and later versions. For new projects, it enables us to craft more expressive and easily understandable asynchronous code, which closely resembles synchronous code. However, adopting async/await may require substantial modifications in existing codebases, especially if their asynchronous API relies heavily on completion handler functions.

Fortunately, Swift offers built-in mechanisms that allow us to create a lightweight wrapper around traditional asynchronous code, facilitating its transition into the async/await paradigm. In this post, I'll demonstrate how to convert callback-based asynchronous code into functions compatible with async/await, using Swift's async keyword.

Converting a Callback-Based Function to Async/Await

Callback-based functions vary in structure, but typically resemble the following example:

func validToken(_ completion: @escaping (Result<Token, Error>) -> Void) {
    // Function body...
}

The validToken(_:) function above is a simplified example, taking a completion closure and using it at various points to return the outcome of fetching a valid token.

Tip: To understand more about @escaping closures, check out this post on @escaping in Swift.

To adapt our validToken function for async/await, we create an async throws version returning a Token. The method signature becomes cleaner:

func validToken() async throws -> Token {
    // ...
}

The challenge lies in integrating the existing callback-based validToken with our new async version. We achieve this through a feature known as continuations. Swift provides several types of continuations:

  • withCheckedThrowingContinuation
  • withCheckedContinuation
  • withUnsafeThrowingContinuation
  • withUnsafeContinuation

These continuations exist in checked and unsafe variants, and in throwing and non-throwing forms. For an in-depth comparison, refer to my post that compares checked and unsafe in great detail.

Here’s the revised validToken function using a checked continuation:

func validToken() async throws -> Token {
    return try await withCheckedThrowingContinuation { continuation in
        // Implementation...
    }
}

This function uses withCheckedThrowingContinuation to bridge our callback-based validToken with the async version. The continuation object, created within the function, must be used to resume execution, or the method will remain indefinitely suspended.

The callback-based validToken is invoked immediately, and once resume is called, the async validToken resumes execution. Since the Result type can contain an Error, we handle both success and failure cases accordingly.

The Swift team has simplified this pattern by introducing a version of resume that accepts a Result object:

func validToken() async throws -> Token {
    return try await withCheckedThrowingContinuation { continuation in
        validToken { result in
            continuation.resume(with: result)
        }
    }
}

This approach is more streamlined and elegant.

Remember two crucial points when working with continuations:

  1. A continuation can only be resumed once.
  2. It's your responsibility to call resume within the continuation closure; failure to do so will leave the function awaiting indefinitely.

Despite minor differences (like error handling), all four with*Continuation functions follow these same fundamental rules.

Summary

This post illustrated how to transform a callback-based function into an async function using continuations. You learned about the different types of continuations and their applications.

Continuations are an excellent tool for gradually integrating async/await into your existing codebase without a complete overhaul. I've personally used them to transition large code segments into async/await gradually, allowing for intermediate layers that support async/await in, say, view models and networking, without needing a full rewrite upfront.

In conclusion, continuations offer a straightforward and elegant solution for converting existing callback-based functions into async/await compatible ones.

Comparing lifecycle management for async sequences and publishers

In my previous post you learned about some different use cases where you might have to choose between an async sequence and Combine while also clearly seeing that async sequence are almost always better looking in the examples I’ve used, it’s time to take a more realistic look at how you might be using each mechanism in your apps.

The details on how the lifecycle of a Combine subscription or async for-loop should be handled will vary based on how you’re using them so I’ll be providing examples for two situations:

  • Managing your lifecycles in SwiftUI
  • Managing your lifecycles virtually anywhere else

We’ll start with SwiftUI since it’s by far the easiest situation to reason about.

Managing your lifecycles in SwiftUI

Apple has added a bunch of very convenient modifiers to SwiftUI that allow us to subscribe to publishers or launch an async task without worrying about the lifecycle of each too much. For the sake of having an example, let’s assume that we have an object that exists in our view that looks a bit like this:

class ExampleViewModel {
    func notificationCenterPublisher() -> AnyPublisher<UIDeviceOrientation, Never> {
        NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
            .map { _ in UIDevice.current.orientation }
            .eraseToAnyPublisher()
    }

    func notificationCenterSequence() async -> AsyncMapSequence<NotificationCenter.Notifications, UIDeviceOrientation> {
        await NotificationCenter.default.notifications(named: UIDevice.orientationDidChangeNotification)
            .map { _ in await UIDevice.current.orientation }
    }
} 

In the SwiftUI view we’ll call each of these two functions to subscribe to the publisher as well as iterate over the async sequence. Here’s what our SwiftUI view looks like:

struct ExampleView: View {
    @State var isPortraitFromPublisher = false
    @State var isPortraitFromSequence = false

    let viewModel = ExampleViewModel()

    var body: some View {
        VStack {
            Text("Portrait from publisher: \(isPortraitFromPublisher ? "yes" : "no")")
            Text("Portrait from sequence: \(isPortraitFromSequence ? "yes" : "no")")
        }
        .task {
            let sequence = await viewModel.notificationCenterSequence()
            for await orientation in sequence {
                isPortraitFromSequence = orientation == .portrait
            }
        }
        .onReceive(viewModel.notificationCenterPublisher()) { orientation in
            isPortraitFromPublisher = orientation == .portrait
        }
    }
}

In this example I’d argue that the publisher approach is easier to understand and use than the async sequence one. Building the publisher is virtually the same as it is for the async sequence with the major difference being the return type of our publisher vs. our sequence: AnyPublisher<UIDeviceOrientation, Never> vs. AsyncMapSequence<NotificationCenter.Notifications, UIDeviceOrientation>. The async sequence actually leaks its implementation details because we have to return an AsyncMapSequence instead of something like an AnyAsyncSequence<UIDeviceOrientation> which would allow us to hide the internal details of our async sequence.

At this time it doesn’t seem like the Swift team sees any benefit in adding something like eraseToAnyAsyncSequence() to the language so we’re expected to provide fully qualified return types in situations like ours.

Using the sequence is also a little bit harder in SwiftUI than it is to use the publisher. SwiftUI’s onReceive will handle subscribing to our publisher and it will provide the publisher’s output to our onReceive closure. For the async sequence we can use task to create a new async context, obtain the sequence, and iterate over it. Not a big deal but definitely a little more complex.

When this view goes out of scope, both the Task created by task as well as the subscription created by onReceive will be cancelled. This means that we don’t need to worry about the lifecycle of our for-loop and subscription.

If you want to iterate over multiple sequences, you might be tempted to write the following:

.task {
    let sequence = await viewModel.notificationCenterSequence()
    for await orientation in sequence {
        isPortraitFromSequence = orientation == .portrait
    }

    let secondSequence = await viewModel.anotherSequence()
    for await output in secondSequence {
        // handle ouput
    }
}

Unfortunately, this setup wouldn’t have the desired outcome. The first for-loop will need to finish before the second sequence is even created. This for-loop behaves just like a regular for-loop where the loop has to finish before moving on to the next lines in your code. The fact that values are produced asynchronously does not change this. To iterate over multiple async sequences in parallel, you need multiple tasks:

.task {
    let sequence = await viewModel.notificationCenterSequence()
    for await orientation in sequence {
        isPortraitFromSequence = orientation == .portrait
    }
}
.task {
    let secondSequence = await viewModel.anotherSequence()
    for await output in secondSequence {
        // handle ouput
    }
}

In SwiftUI, Tasks relatively simple to use, and it’s relatively hard to make mistakes. But what happens if we compare publishers and async sequences lifecycles outside of SwiftUI? That’s what you’ll find out next.

Managing your lifecycles outside of SwiftUI

When you’re subscribing to publishers or iterating over async sequences outside of SwiftUI, things change a little. You suddenly need to manage the lifecycles of everything you do much more carefully, or more specifically for Combine you need to make sure you retain your cancellables to avoid having your subscriptions being torn down immediately. For async sequences you’ll want to make sure you don’t have the tasks that wrap your for-loops linger for longer than they should.

Let’s look at an example. I’m still using SwiftUI, but all the iterating and subscribing will happen in a view model instead of my view:

struct ContentView: View {
    @State var showExampleView = false

    var body: some View {
        Button("Show example") {
            showExampleView = true
        }.sheet(isPresented: $showExampleView) {
            ExampleView(viewModel: ExampleViewModel())
        }
    }
}

struct ExampleView: View {
    @ObservedObject var viewModel: ExampleViewModel
    @Environment(\.dismiss) var dismiss

    var body: some View {
        VStack(spacing: 16) {
            VStack {
                Text("Portrait from publisher: \(viewModel.isPortraitFromPublisher ? "yes" : "no")")
                Text("Portrait from sequence: \(viewModel.isPortraitFromSequence ? "yes" : "no")")
            }

            Button("Dismiss") {
                dismiss()
            }
        }.onAppear {
            viewModel.setup()
        }
    }
}

This setup allows me to present an ExampleView and then dismiss it again. When the ExampleView is presented I want to be subscribed to my notification center publisher and iterate over the notification center async sequence. However, when the view is dismissed the ExampleView and ExampleViewModel should both be deallocated and I want my subscription and the task that wraps my for-loop to be cancelled.

Here’s what my non-optimized ExampleViewModel looks like:

@MainActor
class ExampleViewModel: ObservableObject {
    @Published var isPortraitFromPublisher = false
    @Published var isPortraitFromSequence = false

    private var cancellables = Set<AnyCancellable>()

    deinit {
        print("deinit!")
    }

    func setup() {
        notificationCenterPublisher()
            .map { $0 == .portrait }
            .assign(to: &$isPortraitFromPublisher)

        Task { [weak self] in
            guard let sequence = await self?.notificationCenterSequence() else {
                return
            }
            for await orientation in sequence {
                self?.isPortraitFromSequence = orientation == .portrait
            }
        }
    }

    func notificationCenterPublisher() -> AnyPublisher<UIDeviceOrientation, Never> {
        NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
            .map { _ in UIDevice.current.orientation }
            .eraseToAnyPublisher()
    }

    func notificationCenterSequence() -> AsyncMapSequence<NotificationCenter.Notifications, UIDeviceOrientation> {
        NotificationCenter.default.notifications(named: UIDevice.orientationDidChangeNotification)
            .map { _ in UIDevice.current.orientation }
    }
}

If you’d put the views in a project along with this view model, everything will look good on first sight. The view updates as expected and the ExampleViewModel’s deinit is called whenever we dismiss the ExampleView. Let’s make some changes to setup() to double check that both our Combine subscription and our Task are cancelled and no longer receiving values:

func setup() {
    notificationCenterPublisher()
        .map { $0 == .portrait }
        .handleEvents(receiveOutput: { _ in print("subscription received value") })
        .assign(to: &$isPortraitFromPublisher)

    Task { [weak self] in
        guard let sequence = self?.notificationCenterSequence() else {
            return
        }
        for await orientation in sequence {
            print("sequence received value")
            self?.isPortraitFromSequence = orientation == .portrait
        }
    }.store(in: &cancellables)
}

If you run the app now you’ll find that you’ll see the following output when you rotate your device or simulator after dismissing the ExampleView:

// present ExampleView and rotate
subscription received value
sequence received value
// rotate again
subscription received value
sequence received value
// dismiss
deinit!
// rotate again
sequence received value

You can see that the ExampleViewModel is deallocated and that the subscription no longer receives values after that. Unfortunately, our Task is still active and it’s still iterating over our async sequence. If you present the ExampleView again, you’ll find that you now have multiple active iterators. This is a problem because we want to cancel our Task whenever the object that contains it is deallocated, basically what Combine does with its AnyCancellable.

Luckily, we can add a simple extension on Task to piggy-back on the mechanism that makes AnyCancellable work:

extension Task {
    func store(in cancellables: inout Set<AnyCancellable>) {
        asCancellable().store(in: &cancellables)
    }

    func asCancellable() -> AnyCancellable {
        .init { self.cancel() }
    }
}

Combine’s AnyCancellable is created with a closure that’s run whenever the AnyCancellable itself will be deallocated. In this closure, the task can cancel itself which will also cancel the task that’s producing values for our for-loop. This should end the iteration as long as the task that produces values respects Swift Concurrency’s task cancellation rules.

You can now use this extension as follows:

Task { [weak self] in
    guard let sequence = self?.notificationCenterSequence() else {
        return
    }
    for await orientation in sequence {
        print("sequence received value")
        self?.isPortraitFromSequence = orientation == .portrait
    }
}.store(in: &cancellables)

If you run the app again, you’ll find that you’re no longer left with extraneous for-loops being active which is great.

Just like before, iterating over a second async sequence requires you to create a second task to hold the second iteration.

In case the task that’s producing your async values doesn’t respect task cancellation, you could update your for-loop as follows:

for await orientation in sequence {
    print("sequence received value")
    self?.isPortraitFromSequence = orientation == .portrait

    if Task.isCancelled { break }
}

This simply checks whether the task we’re currently in is cancelled, and if it is we break out of the loop. You shouldn’t need this as long as the value producing task was implemented correctly so I wouldn’t recommend adding this to every async for-loop you write.

One more option to break out of our async for loop is to check whether self still exists within each iteration and either having a return or a break in case self is no longer around:

Task { [weak self] in
    guard let sequence = self?.notificationCenterSequence() else {
        return
    }
    for await orientation in sequence {
        guard let self = self else { return }
        print("sequence received value")
        self.isPortraitFromSequence = orientation == .portrait
    }
}

The nice thing is that we don't to rely on Combine at all with this solution. The downside, however, is that we cannot have a guard let self = self as the first line in our Task because that would capture self for the duration of our Task, which means that every check for self within the for loop body results in self being around. This would be a leak again.

In the example above, we only capture the sequence before starting the loop which means that within the loop we can check for the existence of self and break out of the loop as needed.

Summary

In this post you learned a lot about how the lifecycle of a Combine subscription compares to that of a task that iterates over an async sequence. You saw that using either in a SwiftUI view modifier was pretty straightforward, and SwiftUI makes managing lifecycles easy; you don’t need to worry about it.

However, you also learned that as soon as we move our iterations and subscriptions outside of SwiftUI things get messier. You saw that Combine has good built-in mechanisms to manage lifecycles through its AnyCancellable and even its assign(to:) operator. Tasks unfortunately lack a similar mechanism which means that it’s very easy to end up with more iterators than you’re comfortable with. Luckily, we can add an extension to Task to take care of this by piggy-backing on Combine’s AnyCancellable to cancel our Task objects as soon s the object that owns the task is deallocated.

You also saw that we can leverage a guard on self within each for loop iteration to check whether self is still around, and break out of the loop if self is gone which will stop the iterations.

All in all, Combine simply provides more convenient lifecycle management out of the box when we’re using it outside of SwiftUI views. That doesn’t mean that Combine is automatically better, but it does mean that async sequences aren’t quite in a spot where they are as easy to use as Combine. With a simple extension we can improve the ergonomics of iterating over an async sequence by a lot, but I hope that the Swift team will address binding task lifecycles to the lifecycle of another object like Combine does at some point in the future.

Comparing use cases for async sequences and publishers

Swift 5.5 introduces async/await and a whole new concurrency model that includes a new protocol: AsyncSequence. This protocol allows developers to asynchronously iterate over values coming from a sequence by awaiting them. This means that the sequence can generate or obtain its values asynchronously over time, and provide these values to a for-loop as they become available.

If this sounds familiar, that’s because a Combine publisher does roughly the same thing. A publisher will obtain or generate its values (asynchronously) over time, and it will send these values to subscribers whenever they are available.

While the basis of what we can do with both AsyncSequence and Publisher sounds similar, I would like to explore some of the differences between the two mechanisms in a series of two posts. I will focus this comparison on the following topics:

  • Use cases
  • Lifecycle of a subscription / async for-loop

The post you’re reading now will focus on comparing use cases. If you want to learn more about lifecycle management, take a look at this post.

Please note that parts of this comparison will be highly opinionated or be based on my experiences. I’m trying to make sure that this comparison is fair, honest, and correct but of course my experiences and preferences will influence part of the comparison. Also note that I’m not going to speculate on the futures of either Swift Concurrency nor Combine. I’m comparing AsyncSequence to Publisher using Xcode 13.3, and with the Swift Async Algorithms package added to my project.

Let’s dive in, and take a look at some current use cases where publishers and async sequences can truly shine.

Operations that produce a single output

Our first comparison takes a closer look at operations with a single output. While this is a familiar example for most of us, it isn’t the best comparison because async sequences aren’t made for performing work that produces a single result. That’s not to say an async sequence can’t deliver only one result, it absolutely can.

However, you typically wouldn’t leverage an async sequence to make a network call; you’d await the result of a data task instead.

On the other hand, Combine doesn’t differentiate between tasks that produce a single output and tasks that produce a sequence of outputs. This means that publishers are used for operations that can emit many values as well as for values that produce a single value.

Combine’s approach to publishers can be considered a huge benefit of using them because you only have one mechanism to learn and understand; a publisher. It can also be considered a downside because you never know whether an AnyPublisher<(Data, URLResponse), Error> will emit a single value, or many values. On the other hand, let result: (Data, URLResponse) = try await getData() will always clearly produce a single result because we don’t use an async sequence to obtain a single result; we await the result of a task instead.

Even though this comparison technically compares Combine to async/await rather than async sequences, let’s take a look at an example of performing a network call with Combine vs. performing one with async/await to see which one looks more convenient.

Combine:

var cancellables = Set<AnyCancellable>()

func getData() {
    let url = URL(string: "https://donnywals.com")!
    URLSession.shared.dataTaskPublisher(for: url)
        .sink(receiveCompletion: { completion in
            if case .failure(let error) = completion {
                // handle error
            }
        }, receiveValue: { (result: (Data, URLResponse)) in
            // use result
        })
        .store(in: &cancellables)
}

Async/Await:

func getData() async {
    let url = URL(string: "https://donnywals.com")!
    do {
        let result: (Data, URLResponse) = try await URLSession.shared.data(from: url)
        // use result
    } catch {
        // handle error
    }
}

In my opinion it’s pretty clear which technology is more convenient for performing a task that produces a single result. Async/await is easier to read, easier to use, and requires far less code.

With this somewhat unfair comparison out of the way, let’s take a look at another example that allows us to more directly compare an async sequence to a publisher.

Receiving results from an operation that produces multiple values

Operations that produce multiple values come in many shapes. For example, you might be using a TaskGroup from Swift Concurrency to run several tasks asynchronously, receiving the result for each task as it becomes available. This is an example where you would use an async sequence to iterate over your TaskGroup's results. Unfortunately comparing this case to Combine doesn’t make a lot of sense because Combine doesn’t really have an equivalent to TaskGroup.

💡 Tip: to learn more about Swift Concurrency’s TaskGroup take a look at this post.

One example of an operation that will produce multiple values is observing notifications on NotificationCenter. This is a nice example because not only does NotificationCenter produce multiple values, it will do so asynchronously over a long period of time. Let’s take a look at an example where we observe changes to a user’s device orientation.

Combine:

var cancellables = Set<AnyCancellable>()

func notificationCenter() {
    NotificationCenter.default.publisher(
        for: UIDevice.orientationDidChangeNotification
    ).sink(receiveValue: { notification in
        // handle notification
    })
    .store(in: &cancellables)
}

AsyncSequence:

func notificationCenter() async {
    for await notification in await NotificationCenter.default.notifications(
        named: UIDevice.orientationDidChangeNotification
    ) {
        // handle notification
    }
}

In this case, there is a bit less of a difference than when we used async/await to obtain the result of a network call. The main difference is in how we receive values. In Combine, we use sink to subscribe to a publisher and we need to hold on to the provided cancellable so the subscription is kept alive. With our async sequence, we use a special for-loop where we write for await <value> in <sequence>. Whenever a new value becomes available, our for-loop’s body is called and we can handle the notification.

If you look at this example in isolation I don’t think there’s a very clear winner. However, when we get to the ease of use comparison you’ll notice that the comparison in this section doesn’t tell the full story in terms of the lifecycle and implications of using an async sequence in this example. The next part of this comparison will paint a better picture regarding this topic.

Let’s look at another use case where you might find yourself wondering whether you should reach for Combine or an async sequence; state observation.

Observing state

If you’re using SwiftUI in your codebase, you’re making extensive use of state observation. The mix of @Published and ObservableObject on data sources external to your view allow SwiftUI to determine when a view’s source of truth will change so it can potentially schedule a redraw of your view.

💡 Tip: If you want to learn more about how and when SwiftUI decided to redraw views, take a look at this post.

The @Published property wrapper is a special kind of property wrapper that uses Combine’s CurrentValueSubject internally to emit values right before assigning these values as the wrapped property’s current value. This means that you can subscribe to @Published using Combine’s sink to handle new values as they become available.

Unfortunately, we don’t really have a similar mechanism available that only uses Swift Concurrency. However, for the sake of the comparison, we’ll make this example work by leveraging the values property on Publisher to convert our @Published publisher into an async sequence.

Combine:

@Published var myValue = 0

func stateObserving() {
    $myValue.sink(receiveValue: { newValue in

    }).store(in: &cancellables)
}

Async sequence:

@Published var myValue = 0

func stateObserving() async {
    for await newValue in $myValue.values {
        // handle new value
    }
}

Similar to before, the async sequence version looks a little bit cleaner than the Combine version but as you’ll find in the next post, this example doesn’t quite tell the full story of using an async sequence to observe state. The lifecycle of an async sequence can, in certain case complicate our example quite a lot so I really recommend that you also check out the lifecycle comparison to gain a much better understanding of an async sequence’s lifecycle.

It’s also important to keep in mind that this example uses Combine to facilitate the actual state observation because at this time Swift Concurrency does not provide us with a built-in way to do this. However, by converting the Combine publisher to an async sequence we can get a pretty good sense of what state observation could look like if/when support for this is added to Swift.

Summary

In this post, I’ve covered three different use cases for both Combine and async sequences. It’s pretty clear that iterating over an async sequence looks much cleaner than subscribing to a publisher. There’s also no doubt that tasks with a single output like network calls look much cleaner with async/await than they do with Combine.

However, these examples aren’t quite as balanced as I would have liked them to be. In all of the Combine examples I took into account the lifecycle of the subscriptions I created because otherwise the subscriptions wouldn’t work due to the cancellable that’s returned by sink being deallocated if it’s not retained in my set of cancellables.

The async sequence versions, however, work fine without any lifecycle management but there’s a catch. Each of the functions I wrote was async which means that calling those functions must be done with an await, and the caller is suspended until the async sequence that we’re iterating over completes. In the examples of NotificationCenter and state observation the sequences never end so we’ll need to make some changes to our code to make it work without suspending the caller.

We’ll take a better look at this in the next post.

What is the “any” keyword in Swift?

With Swift 5.6, Apple added a new keyword to the Swift language: any. As you'll see in this post, usage of the any keyword looks very similar to how you use the some keyword. They're both used in front of protocol names, and they both tell us something about how that protocol is used. Once you dig deeper into what any means, you'll find that it's very different from some. In fact, you might come to the conclusion that any is somewhat of the opposite of some. In this post, you will learn everything you need to know about the any keyword in Swift as well as existentials, and what they are.

Let’s dive right into the any keyword by taking a look at its intended use in a very simple example:

protocol Networking {
    func fetchPosts() async throws -> [Post]
    // ...
}

struct PostsDataSource {
    let networking: any Networking
    // ...
}

💡Tip: If you’re not familiar with Swift’s some keyword or need a refresher, check out this post on Swift’s some keyword.

While the any keyword might look similar to the some keyword in the sense that both are used in front of a protocol, and sound like they convey a message similar to “I don’t care what’s used for this type as long as it conforms to this protocol”, they’re really not the same at all. To understand their differences, we need to take a look at what existentials are in Swift.

Understanding what an existential is in Swift

While some allows us to write code that more or less ignores, or discards, a protocol’s associated type and/or Self requirement while expecting that every returned object in a function that returns some Protocol has the same concrete type, the any keyword simply annotates that a given type is a so-called existential. While you might not know what an existential is, you've probably seen them used. For example, if we look at the "old" way of writing the PostsDataSource struct that you just saw, it would look as follows:

struct PostsDataSource {
    let networking: Networking
    // ...
}

Note that all I did is remove the any keyword. The Networking object that we use is an existential. This means that let networking is an object that conforms to Networking. The compiler doesn't know which object it will be, or what that object's type is. All the compiler knows is that there will be an object, any object, that will be assigned to let networking when we initialize PostsDataSource, and that object conforms to Networking. We're essentially only sure that we'll have a box that contains a Networking object. To know exactly which object was put in that box, we need to open that box at runtime, peek inside, and find the object.

It's important to know that existentials are relatively expensive to use because the compiler and runtime can’t pre-determine how much memory should be allocated for the concrete object that will fill in the existential. Whenever you call a method on an existential, like the networking property in the snippet you saw earlier, the runtime will have to dynamically dispatch this call to the concrete object which is slower than a static dispatch that goes directly to a concrete type.

The Swift team has determined that it’s currently too easy to reach for an existential over a concrete object. This essentially means that a lot of us are writing code that uses protocols (existentials) that harm our performance without us really being aware of it. For example, there’s nothing wrong with the old fashioned PostsDataSource you saw earlier, right?

struct PostsDataSource {
    let networking: Networking
    // ...
}

I’m sure we all have code like this, and in fact, we might even consider this best practice because we're not depending on concrete types which makes our code easier to test and maintain.

Sadly, this code uses an existential by having a property that has Networking as its type. This means that it’s not clear for the runtime how much memory should be allocated for the object that will fill in our networking property, and any calls to fetchPosts will need to be dynamically dispatched.

By introducing the any keyword, the language forces us to think about this. In Swift 5.6 annotating our let networking: Networking with any is optional; we can do this on our own terms. However, in Swift 6 it will be required to annotate existentials with the any keyword.

Verify your existential usage for Swift 6 with Xcode 15.3

If you want to make sure that your app is ready for Swift 6.0 and uses any or some everywhere you're supposed to, pass the -enable-upcoming-feature ExistentialAny in your Swift build flags. To learn how, take a look at this post where I dig into experimental Swift versions and features. Note that the EsistentialAny build flag is available in the default Xcode 15.3 toolchain.

Digging deeper into the any keyword

As I was reading the proposal for any, I realized that what the Swift team seems to want us to do, is to use generics and concrete types rather than existentials when possible. It’s especially this part from the introduction of the proposal that made this clear to me:

Despite these significant and often undesirable implications, existential types have a minimal spelling. Syntactically, the cost of using one is hidden, and the similar spelling to generic constraints has caused many programmers to confuse existential types with generics. In reality, the need for the dynamism they provided is relatively rare compared to the need for generics, but the language makes existential types too easy to reach for, especially by mistake. The cost of using existential types should not be hidden, and programmers should explicitly opt into these semantics.

So how should we be writing our PostsDataSource without depending on a concrete implementation directly? And how can we do that without using an existential since clearly existentials are less than ideal?

The easiest way would be to add a generic to our PostsDataSource and constraining it to Networkingas follows:

protocol Networking {
    func fetchPosts() async throws -> [Post]
    // ...
}

struct PostsDataSource<Network: Networking> {
    let networking: Network
    // ...
}

By writing our code like this, the compiler will know up front which type will be used to fill in the Network generic. This means that the runtime will know up-front how much memory needs to be allocated for this object, and calls to fetchPosts can be dispatched statically rather than dynamically.

💡Tip: If you’re not too familiar with generics, take a look at this article to learn more about generics in Swift and how they’re used.

When writing PostsDataSource as shown above, you don’t lose anything valuable. You can still inject different concrete implementations for testing, and you can still have different instances of PostsDataSource with different networking objects even within your app. The difference compared to the previous approach is that the runtime can more efficiently execute your code when it know the concrete types you’re using (through generics).

Alternatively, you could rewrite let networking to use some Networking instead of using a generic. To learn more about some, and how you can use it to replace generics in some situations, take a look at this post.

The only thing we’ve lost by not using any is the ability to dynamically swap out the networking implementation at runtime by assigning a new value of a different concrete type to networking (which we couldn’t do anyway because it’s defined as a let).

It's interesting to note that because we have to choose between any, some, and a generic, when we define our let networking, it's easier to choose the correct option. We could use : any Networking wherever we'd write : Networking in Swift 5.5 and earlier, and our code would work just fine but we might be using a suboptimal existential instead of a concrete type that can benefit from compile-time optimizations and static dispatch at runtime. In some cases, that's exactly what you want. You might need the flexibility that an existential provides, but often you'll find that you don't need an existential at all.

So how useful is the any keyword really? Should you be using it in Swift 5.6 already or is it better to just wait until the compiler starts enforcing any in Swift 6?

In my opinion, the any keyword will provide developers with an interesting tool that forces them to think about how they write code, and more specifically, how we use types in our code. Given that existentials have a detrimental effect on our code’s performance I’m happy to see that we need to explicitly annotate existentials with a keyword in Swift 6 onward. Especially because it’s often possible to use a generic instead of an existential without losing any benefits of using protocols. For that reason alone it’s already worth training yourself to start using any in Swift 5.6.

Note: take a look at my post comparing some and any to learn a bit more about how some can be used in place of a generic in certain situations.

Using any now in Swift 5.6 will smoothen your inevitable transition to Swift 6 where the following code would actually be a compiler error:

protocol Networking {
    func fetchPosts() async throws -> [Post]
    // ...
}

struct PostsDataSource {
    // This is an error in Swift 6 because Networking is an existential
    let networking: Networking
    // ...
}

The above code will at least need to be written using any Networking in Swift if you really need the existential Networking. In most cases however, this should prompt you to reconsider using the protocol in favor of a generic or writing some Networking in order to improve runtime performance.

Whether or not the performance gains from using generics over existentials is significant enough to make a difference in the average app remains to be seen. Being conscious of the cost of existentials in Swift is good though, and it’s definitely making me reconsider some of the code I have written.

The any keyword in Swift 5.7

In Swift 5.7 the any keyword is still not mandatory for all existentials but certain features aren't available to non-any protocols. For example, in Swift 5.7 the requirements around protocols with a Self requirement have been relaxed. Previously, if you wanted to use a protocol with an associated type of Self requirement as a type you would have to use some. This is why you have to write var body: some View in SwiftUI.

In Swift 5.7 this restriction is relaxed, but you have to write any to use an existential that has an associated type or Self requirement. The following example is an example of this:

protocol Content: Identifiable {
    var url: URL { get }
}

func useContent(_ content: any Content) {
    // ...
}

The code above requires us to use any Content because Content extends the Identifiable protocol which has an associated type (defined as associatedtype ID: Hashable). For that reason, we have to use any if we can't use some.

The same is true for protocols that use a primary associated type. Using an existential with a primary associated type already requires the any keyword in Swift 5.7.

Note that any isn't a drop in replacement for some as noted in my comparison of these two keywords. When using any, you'll always opt-in to using an existential rather than a concrete type (which is what some would provide).

Even though any won't be completely mandatory until Swift 6.0 it's interesting to see that Swift 5.7 already requires any for some of the new features that were made available with Swift 5.7. I think this reinforces the point that I made earlier in this post; try to start using any today so you're not surprised by compiler errors once Swift 6.0 drops.

Writing custom property wrappers for SwiftUI

It's been a while since I published my post that helps you wrap your head around Swift's property wrappers. Since then, I've done more and more SwiftUI related work and one challenge that I recently had to dig into was passing dependencies from SwiftUI's environment into a custom property wrapper.

While figuring this out I learned about the DynamicProperty protocol which is a protocol that you can conform your property wrappers to. When your property wrapper conforms to the DynamicProperty protocol, your property wrapper will essentially become a part of your SwiftUI view. This means that your property wrapper can extract values from your SwiftUI environment, and your SwiftUI view will ask your property wrapper to update itself whenever it's about to evaluate your view's body. You can even have @StateObject properties in your property wrapper to trigger updates in your views.

This protocol isn't limited to property wrappers, but for the sake of this post I will explore DynamicProperty in the context of a property wrapper.

Understanding the basics of DynamicProperty

Defining a dynamic property is as simple as conforming a property wrapper to the DynamicProperty protocol. The only requirement that this protocol has is that you implement an update method that's called by your view whenever it's about to evaluate its body. Defining such a property wrapper looks as follows:

@propertyWrapper
struct MyPropertyWrapper: DynamicProperty {
  var wrappedValue: String

  func update() {
    // called whenever the view will evaluate its body
  }
}

This example on its own isn't very useful of course. I'll show you a more useful custom property wrapper in a moment. Let's go ahead and take a moment to explore what we've defined here first.

The property wrapper that we've defined here is pretty straightforward. The wrapped value for this wrapper is a string which means that it'll be used as a string in our SwiftUI view. If you want to learn more about how property wrappers work, take a look at this post I published on the topic.

There's also an update method that's called whenever SwiftUI is about to evaluate its body. This function allows you to update state that exists external to your property wrapper. You’ll often find that you don’t need to implement this method at all unless you’re doing a bunch of more complex work in your property wrapper. I’ll show you an example of this towards the end of the article.

⚠️ Note that I’ve defined my property wrapper as a struct and not a class. Defining a DynamicProperty property wrapper as a class is allowed, and works to some extent, but in my experience it produces very inconsistent results and a lot of things you might expect to work don’t actually work. I’m not quite sure exactly why this is the case, and what SwiftUI does to break property wrappers that were defined as classes. I just know that structs work, and classes don’t.

One pretty neat thing about a DynamicProperty is that SwiftUI will pick it up and make it part of the SwiftUI environment. What this means is that you have access to environment values, and that you can leverage property wrappers like @State and @ObservedObject to trigger updates from within your property wrapper.

Let’s go ahead and define a property wrapper that hold on to some state and updates the view whenever this state changes.

Triggering view updates from your dynamic property

Dynamic properties on their own can’t tell a SwiftUI view to update. However, we can use @State, @ObservedObject, @StateObject and other SwiftUI property wrappers to trigger view updates from within a custom property wrapper.

A simple example would look a little bit like this:

@propertyWrapper
struct CustomProperty: DynamicProperty {
    @State private var value = 0

    var wrappedValue: Int {
        get {
            return value
        }

        nonmutating set {
            value = newValue
        }
    }
}

This property wrapper wraps an Int value. Whenever this value receives a new value, the @State property value is mutated, which will trigger a view update. Using this property wrapper in a view looks as follows:

struct ContentView: View {
    @CustomProperty var customProperty

    var body: some View {
        Text("Count: \(customProperty)")

        Button("Increment") {
            customProperty += 1
        }
    }
}

The SwiftUI view updates the value of customProperty whenever a button is tapped. This on its own does not trigger a reevaluation of the body. The reason our view updates is because the value that represents our wrapped value is marked with @State. What’s neat about this is that if value changes for any reason, our view will update.

A property wrapper like this is not particularly useful, but we can do some pretty neat things to build abstractions around different kinds of data access. For example, you could build an abstraction around UserDefaults that provides a key path based version of AppStorage:

class SettingKeys: ObservableObject {
    @AppStorage("onboardingCompleted") var onboardingCompleted = false
    @AppStorage("promptedForProVersion") var promptedForProVersion = false
}

@propertyWrapper
struct Setting<T>: DynamicProperty {
    @StateObject private var keys = SettingKeys()
    private let key: ReferenceWritableKeyPath<SettingKeys, T>

    var wrappedValue: T {
        get {
            keys[keyPath: key]
        }

        nonmutating set {
            keys[keyPath: key] = newValue
        }
    }

    init(_ key: ReferenceWritableKeyPath<SettingKeys, T>) {
        self.key = key
    }
}

Using this property wrapper would look as follows:

struct ContentView: View {
    @Setting(\.onboardingCompleted) var didOnboard

    var body: some View {
        Text("Onboarding completed: \(didOnboard ? "Yes" : "No")")

        Button("Complete onboarding") {
            didOnboard = true
        }
    }
}

Any place in the app that uses @Setting(\.onboardingCompleted) var didOnboard will automatically update when the value for onboarding completed in user defaults updated, regardless of where / how this happened. This is exactly the same as how @AppStorage works. In fact, my custom property wrapper relies heavily on @AppStorage under the hood.

My SettingsKeys object wraps up all of the different keys I want to write to in UserDefaults, the @AppStorage property wrapper allows for easy observation and makes it so that I can define SettingsKeys as an ObservableObject without any troubles.

By implementing a custom get and set on my Setting<T>'s wrappedValue, I can easily read values from user defaults, or write a new value simply by assigning to the appropriate key path in SettingsKeys.

Simple property wrappers like these are very useful when you want to streamline some of your data access, or if you want to add some semantic meaning and ease of discovery to your property wrapper.

To see some more examples of simple property wrappers (including a user defaults one that inspired the example you just saw), take a look at this post from Dave Delong.

Using SwiftUI environment values in your property wrapper

In addition to triggering view updates via some of SwiftUI’s property wrappers, it’s also possible to access the SwiftUI environment for the view that your property wrapper is used in. This is incredibly useful when your property wrapper is more complex and has a dependency on, for example, a managed object context, a networking object, or similar objects.

Accessing the SwiftUI environment from within your property wrapper is done in exactly the same way as you do it in your views:

@propertyWrapper
struct CustomFetcher<T>: DynamicProperty {
    @Environment(\.managedObjectContext) var managedObjectContext

    // ...
}

Alternatively, you can read environment objects that were assigned through your view with the .environmentObject view modifier as follows:

@propertyWrapper
struct UsesEnvironmentObject<T: ObservableObject>: DynamicProperty {
    @EnvironmentObject var envObject: T

    // ...
}

We can use the environment to conveniently pass dependencies to our property wrappers. For example, let’s say you’re building a property wrapper that fetches data from the network. You might have an object named Networking that can perform network calls to fetch the data you need. You could inject this object into the property wrapper through the environment:

@propertyWrapper
struct FeedLoader<Feed: FeedType>: DynamicProperty {
    @Environment(\.network) var network

    var wrappedValue: [Feed.ObjectType] = []
}

The network environment key is a custom key that I’ve added to my SwiftUI environment. To learn more about adding custom values to the SwiftUI environment, take a look at this tip I posted earlier.

Now that we have this property wrapper defined, we need a way to fetch data from the network and assign it to something in order to update our wrapped value. To do this, we can implement the update method that allows us to update data that’s referenced by our property wrapper if needed.

Implementing the update method for your property wrapper

The update method that’s part of the DynamicProperty protocol allows you to respond to SwiftUI’s body evaluations. Whenever SwiftUI is about to evaluate a view’s body, it will call your dynamic property’s update method.

💡 To learn more about how and when SwiftUI evaluates your view’s body, take a look at this post where I explore body evaluation in depth.

As mentioned earlier, you won’t often have a need to implement the update method. I’ve personally found this method to be handy whenever I needed to kick off some kind of data fetching operation. For example, to fetch data from Core Data in a custom implementation of @FetchRequest, or to experiment with fetching data from a server. Let’s expand the FeedLoader property wrapper from earlier a bit to see what a data loading property wrapper might look like:

@propertyWrapper
struct FeedLoader<Feed: FeedType>: DynamicProperty {
    @Environment(\.network) var network
    @State private var feed: [Feed.ObjectType] = []
    private let feedType: Feed
    @State var isLoading = false

    var wrappedValue: [Feed.ObjectType] {
        return feed
    }

    init(feedType: Feed) {
        self.feedType = feedType
    }

    func update() {
        Task {
            if feed.isEmpty && !isLoading {
                self.isLoading = true
                self.feed = try await network.load(feedType.endpoint)
                self.isLoading = false
            }
        }
    }
}

This is a very, very simple implementation of a property wrapper that uses the update method to go to the network, load some data, and assign it to the feed property. We have to make sure that we only load data if we’re not already loading, and we also need to check whether or not the feed is currently empty to avoid loading the same data every time SwiftUI decides to re-evaluate our view’s body.

This of course begs the question, should you use a custom property wrapper to load data from the network? And the answer is, I’m not sure. I’m still heavily experimenting with the update method, its limitations, and its benefits. One thing that’s important to realize is that update is called every time SwiftUI is about to evaluate a view’s body. So synchronously assigning a new value to an @State property from within that method is probably not the best idea; Xcode even shows a runtime warning when I do this.

At this point I’m fairly sure Apple intended update to be used for updating or reading state external to the property wrapper rather than it being used to synchronously update state that’s internal to the property wrapper.

On the other hand, I’m positive that @FetchRequest makes heavy use of update to refetch data whenever its predicate or sort descriptors have changed, probably in a somewhat similar way that I’m fetching data from the network here.

Summary

Writing custom property wrappers for your SwiftUI views is a fun exercise and it’s possible to write some very convenient little helpers to improve your experience while writing SwiftUI views. The fact that your dynamic properties are connected to the SwiftUI view lifecycle and environment is super convenient because it allows you to trigger view updates, and read values from SwiftUI’s environment.

That said, documentation on some of the details surrounding DynamicProperty is severely lacking which means that we can only guess how mechanisms like update() are supposed to be leverages, and why structs work perfectly fine as dynamic properties but classes don’t.

These are some points that I hope to be able to expand on in the future, but for now, there are definitely still some mysteries for me to unravel. And this is where you come in! If you have any additions for this posts, or if you have a solid understanding of how update() was meant to be used, feel free to send me a Tweet. I’d love to hear from you.

Adding custom keys to the SwiftUI environment

In Xcode 16, it's possible to add custom keys using the convenient @Entry macro.

Sometimes you’ll find yourself in a situation where you want to conveniently pass some object down via the SwiftUI environment. An easy way to do this is through the .environmentObject view modifier. The one downside of this view modifier and corresponding @EnvironmentObject property wrapper is that the object you add to the environment must be an observable object.

Luckily, we can extend the SwiftUI environment to add our own objects to the @Environment property wrapper without the need to make these objects observable.

For example, your app might have to do some date formatting, and maybe you’re looking for a convenient way to pass a default date formatter around to your views without explicitly passing this date formatter around all the time. The SwiftUI environment is a convenient way to achieve this.

To add our date formatter to the environment, we need to define an EnvironmentKey, and we need to add a computed property to the EnvironmentValues object. Here’s what this looks like:

private struct DateFormatterKey: EnvironmentKey {
    static let defaultValue: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "MM/dd/yyyy"
        return formatter
    }()
}

extension EnvironmentValues {
    var dateFormatter: DateFormatter {
        get { self[DateFormatterKey.self] }
        set { self[DateFormatterKey.self] = newValue }
    }
}

This code conveniently sets up a default date formatter (which is required by the EnvironmentKey protocol). I’ve also added a computed property to EnvironmentValues to make the date formatter object available in my SwiftUI views.

Using this custom environment value is done as follows:

struct LabelView: View {
    @Environment(\.dateFormatter) var dateFormatter
    @State var date: Date

    var body: some View {
        Text("date: \(dateFormatter.string(from: date))")
    }
}

Adding your own keys to the SwiftUI environment can be done for all kinds of reasons. You can use the environment for small objects like the date formatter in this example. But you can even use the environment to pass around more complex objects. For example, you could pass your networking stack around through the SwiftUI environment if this suits your needs.

Hopefully this quick tip is useful for you! I’d love to hear about the kind of things you’re using the SwiftUI environment for in your apps, so make sure to shoot me a Tweet if you’d like to tell me about your experiences.

Five things iOS developers should focus on in 2022

A new year has started and most of us are probably figuring out what we should focus on this year. Whether it’s learning new things or expanding our knowledge on topics we’ve already learned about in the past, there’s always something that deserves our attention in the world of iOS development.

In this short post I’ve listed five things that I believe will help you become a better developer in 2022. Or rather, the first half of 2022. I’m fully expecting Apple to release some cool new interesting things at this year’s WWDC that deserve some of your attention in the second half of the year.

That said, if you focus on the five things listed in this post I’m sure you’ll come out as a stronger developer by the end of the year.

Please not that this list should not be treated as the “definitive” guide to becoming a good developer in 2022. Nor is it a list of the most important topics for everybody that does iOS development.

It’s a list of topics that I believe to be important, and it’s a list of topics that will take up a lot of my time this year. If you disagree with this list, that’s absolutely okay; your priorities do not have to align with mine.

With that out of the way, let’s jump into the first topic on my list.

1. Using SwiftUI alongside UIKit (and vice versa)

One of the most polarising questions I’ve seen in 2021 is probably whether or not SwiftUI is “production ready”. In my opinion that question is way too vague because the answer depends on what an individual’s definition of production ready is within their context. What’s more important in my opinion is the fact that SwiftUI can be used in your apps just fine. Whether you want to go all-in or not, that you’re choice. There are even cases where going all-in on SwiftUI isn’t quite possible for various reasons.

The vast majority of apps I’ve seen and worked on in the past year can get really far with just plain SwiftUI but almost always there are some edges where dropping down to UIKit was needed. Alternatively, I’ve seen existing production apps that wanted to start integrating SwiftUI without rewriting everything straight away which is completely reasonable.

Luckily, we can use SwiftUI and UIKit simultaneously in our projects and I would highly encourage folks to do this. Make sure you dig and understand how to mix SwiftUI into a UIKit app, or how you can fall back to UIKit in a SwiftUI app if you find that you’re running into limitations with purely using SwiftUI.

Knowing how to do this will allow you to adopt SwiftUI features where possible, and speed up your development process because writing UI with SwiftUI is so much faster than UIKit (when it suits your needs). On top of that, it will take a while for companies to have all their apps written exclusively in SwiftUI so knowing how to gradually introduce it is a really valuable skill to have as an employee or even as someone who’s looking for their next (or their first) job.

2. App Architecture

No, I don’t mean “learn VIPER” or “learn all the architectures”. In fact, I’m not saying you should learn any app architecture in particular.

In my opinion it’s far more valuable to understand the principles that virtually every architecture is built upon; separation of concerns. Knowing how and when to split your app’s functionality into different components, and knowing how these components should be structured is extremely important when you want to write code that’s easy to reason about, easy to refactor, and easy to test.

Try and learn about topics such as single responsibility principle, dependency injection, abstractions, protocols, generics, and more. Once you’ve learned about these topics, you’ll find a lot of the architectural patterns out there are just different applications of the same principles. In other words, lots of architectures provide a framework for you and your team to reason about different layers in your codebase rather that a completely unique way of working.

A less obvious reason to learn more about app architecture is that it will help you write code that can work in a SwiftUI world as well as a UIKit world which is extremely useful given what I explained in the first point on this list. The ability to architect a codebase that works with both SwiftUI and UIKit is extremely useful and will definitely help you enjoy the experience of mixing UI frameworks more.

3. Async-Await

If there’s one topic that I just couldn’t leave off this list it’s async-await. Or rather, Swift’s new concurrency model. With the introduction of async-await Apple didn’t just introduce some syntactic sugar (like how async-await is essentially sugar over promises in JavaScript). Apple introduce a whole new modern concurrency system that we can leverage in our apps.

Topics like structured concurrency, actors, task groups, and more are extremely useful to learn about this year. Especially because Apple’s managed to backport Swift Concurrency all the way to iOS 13. Make sure you’re using Xcode 13.2 or newer if you want to use Swift Concurrency in apps that target iOS 13.0 and up, and you should be good to go.

If you want to learn more about Swift Concurrency, I have a couple posts available on my blog already. Click here to go to the Swift Concurrency category.

4. Core Data

Yes. It’s a pretty old framework and its Objective-C roots are not very well hidden. Regardless, Apple’s clearly still interested in having people use and adopt Core Data given the fact that they’ve added new features for Core Data + SwiftUI in iOS 15, and previous iOS versions received various Core Data updates too.

Will Apple replace Core Data with a more Swift-friendly alternative soon? I honestly don’t know. I don’t think it’s likely that Apple will do a complete replacement any time soon. It seems more likely for Apple to keep Core Data’s core bits and provide us a more Swift-friendly API on top of this. That way the transition from the current API to a newer API can be done step by step, and our apps won’t have to go through some major migration if we want to leverage the latest and greatest. Pretty similar to how Apple is introducing SwiftUI.

Is Core Data the absolute best way to persist data in all cases? Probably not. Is it extremely difficult to implement and way too heavy for most apps? No, not at all. Core Data really isn’t that scary, and it integrates with SwiftUI really nicely. Check out this video I did on using Core Data in a SwiftUI application for example:

If you want to learn more about Core Data this year, I highly recommend you pick up my Practical Core Data book. It teaches you everything you need to know to make use of Core Data effectively in both SwiftUI and UIKit applications.

5. Accessibility

Last but by no means least on my list is a topic that I myself should learn more about. Accessibility is often considered optional, a “feature”, or something you do last in your development process. Or honestly, it’s not even rare for accessibility to not be considered on a roadmap at all.

When you think of accessibility like that, there’s a good chance your app isn’t accessible at all because you never ended up doing the work. I’m not entirely sure where I’ve heard this first but if you’re not sure whether your app is accessible or not, it isn’t.

Accessibility is something we should actively keep an eye on to make sure everybody can use our apps. Apple’s tools for implementing and testing accessibility are really good, and I have to admit I know far too little about them. So for 2022, accessibility is absolutely on my list of things to focus on.

Forcing an app out of memory on iOS

I’ve recently been working on a background uploading feature for an app. One of the key aspects to get right with a feature like that is to correctly handle scenarios where your app is suspended by the system due to RAM constraints or other, similar, reasons. Testing this is easily done by clearing the RAM memory on your device. Unfortunately, this isn’t straightforward. But it’s also not impossible.

Note that opening the task switcher and force closing your app from there is not quite the same as forcing your app to be suspended. Or rather, it’s not the same as forcing your app out of memory.

Luckily, there’s somewhat of a hidden trick to clear your iOS device’s RAM memory, resulting in your app getting suspended just like it would if the device ran out of memory due to something your user is doing.

To force-clear your iOS device’s RAM memory, go through the following steps:

  1. If you’re using a device without a home button, enable Assistive Touch. If your device has a home button you can skip this step. You can enable Assistive Touch by going to Settings → Accessibility → Touch → Enable Assistive Touch. This will make a floating software button appear on your device that can be tapped to access several shortcuts, a virtual home button is one of these shortcuts.

Settings window for accessibility -> touch -> assistive touch

  1. In a (somewhat) fluid sequence press volume up, volume down, and then hold your device’s power button until a screen appears that allows you to power down your device.
  2. Once that screen appears, tap the assistive touch button and then press and hold the virtual home button until you’re prompted to unlock your device. You’ve successfully wiped your device’s RAM memory.

Shut down screen with assistive touch actions visible

Being able to simulate situations where your app goes out of memory is incredibly useful when you’re working on features that rely on your app being resumed in the background even when it’s out of memory. Background uploads and downloads are just some examples of when this trick is useful.

My favorite part of using this approach to debug my apps going out of memory is that I can do it completely detached from Xcode, and I can even ask other people like a Q&A department to test with this method to ensure everything works as expected.

An app that's forced out of ram is not considered closed because it's still present in the app switcher, and any background processes continue to run. during normal device usage, apps will be forced out of ram whenever ann app that the user is using needs more ram, of if a user hasn't opened your app in a while. When the user launches your app the app will still boot as a fresh launch with the main difference being that the app might have done work in the background.

When an app is force closed from the app switcher, iOS does not allow this app to continue work in the background, so any in progress uploads or other tasks are considered cancelled.