Reader small image

You're reading from  SwiftUI Cookbook - Third Edition

Product typeBook
Published inDec 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805121732
Edition3rd Edition
Languages
Tools
Concepts
Right arrow
Author (1)
Juan C. Catalan
Juan C. Catalan
author image
Juan C. Catalan

Juan C. Catalan is a software engineer with more than 18 years of professional experience. He started mobile development back in the days of iOS 3. Juan has worked as a professional iOS developer in many industries, including medical devices, financial services, real estate, document management, fleet tracking and industrial automation. He has contributed to more than 30 published apps in the App Store, some of them with millions of users. Juan gives back to the iOS development community with technical talks, mentoring developers, reviewing technical books and now as a book author. He lives in Austin, Texas, with his wife Donna, where they spend time with their kids.
Read more about Juan C. Catalan

Right arrow

SwiftUI Concurrency with async await

One of the most important features of Swift 5.5, introduced in iOS 15, was the introduction of the async and await keywords. With async and await, we can write asynchronous concurrent code almost as if it were synchronous code, one statement after the other.

Concurrency means that different pieces of code run at the same time. Often, we must orchestrate these pieces of code to create sequences of events to present the results in a view.

Before Swift 5.5, the most common way of creating a sequence of concurrent code was by using a completion block. When the first part of the code finishes, we call a completion block where we start the second piece of code. This works and is manageable if we have only two asynchronous functions to synchronize, but it would become quickly unmaintainable with multiple functions and different ways of synchronizing them. For example, we could have two asynchronous functions to wait for before starting the third...

Technical requirements

The code in this chapter is based on Xcode 15.0 and iOS 17.0. You can download and install the latest version of Xcode from the App Store. You’ll also need to be running macOS Ventura (13.5) or newer.

Simply search for Xcode in the App Store and select and download the latest version. Launch Xcode and follow any additional installation instructions that your system may prompt you with. Once Xcode has fully launched, you’re ready to go.

All the code examples for this chapter can be found on GitHub at https://github.com/PacktPublishing/SwiftUI-Cookbook-3rd-Edition/tree/main/Chapter12-SwiftUI-concurrency-with-async-await.

Integrating SwiftUI and an async function

As mentioned in the introduction of this chapter, the async await model fits well with the SwiftUI model.

SwiftUI views offer support for calling asynchronous functions. Also, while a function is concurrently executing, we can change the view without having it blocked.

In this short recipe, we’ll integrate an async function that suspends its execution for a few seconds and, at the same time, verify that the UI interaction is not blocked, and we can use a button to increase a counter shown in the view.

Getting ready

Create a SwiftUI app called AsyncAwaitSwiftUI.

How to do it…

We will create a simple app with a button that increases a counter and an asynchronous function that blocks for 5 seconds before returning a value to be presented in the view.

The steps are as follows:

  1. Create a Service class with the following two functions:
    class Service {    
        func fetchResult() async -...

Fetching remote data in SwiftUI

One of the operations made easier by the async await model is network data transfer operations. Fetching data from a network resource is an asynchronous operation by definition and until now, we had to manage it with the completion block mechanism.

iOS 15 added an async await interface to the URLSession class to embrace the new pattern. In this recipe, we’ll implement a class to download data from a remote service and present it in a SwiftUI view.

We’ll use a free service called JSONPlaceholder (https://jsonplaceholder.typicode.com) that provides a free fake API for testing purposes. The service has multiple resources with relations among them.

The app we’ll implement will have a view with a list of fake users to choose from, and another view to present the different fake blog posts for the user we selected.

Getting ready

Create a SwiftUI app called FakePosts.

How to do it…

We are going to implement...

Join our book community on Discord

https://packt.link/iosdevelopment

Qr code Description automatically generated

In this chapter, we'll learn how to manage the state of SwiftUI views using Combine. At the Worldwide Developers Conference (WWDC) 2019, Apple not only introduced SwiftUI but also Combine, a perfect companion to SwiftUI for managing the declarative change of state in Swift. In recent years, given the success of Functional Reactive Programming (FRP) in different sectors of the industry, the same concept has been used in the iOS ecosystem. It was first implemented with ReactiveCocoa, the original framework in Objective-C. That framework was converted into Swift with ReactiveSwift. Finally, it was converted into RxSwift, which became the default framework for performing FRP in iOS. In typical Apple way, Apple took the best practices that have matured over years of trial and error from the community, and instead of acquiring either ReactiveSwift or RxSwift, Apple decided to reimplement their concepts, simplify their...

Technical requirements

  1. The code in this chapter is based on Xcode 15.0 and iOS 17.0. You can download and install the latest version of Xcode from the App Store. You'll also need to be running macOS Ventura (13.5) or newer.
  2. Simply search for Xcode in the App Store and select and download the latest version. Launch Xcode and follow any additional installation instructions that your system may prompt you with. Once Xcode has fully launched, you're ready to go.
  3. All the code examples for this chapter can be found on GitHub at https://github.com/PacktPublishing/SwiftUI-Cookbook-3rd-Edition/tree/main/Chapter11-Driving-SwiftUI-with-Combine.

Introducing Combine in a SwiftUI project

In this recipe, we are going to add publish support to CoreLocation, which is an Apple framework that provides location services such as the current position of the user. The CLLocationManager framework class will emit status and location updates, which will be observed by a SwiftUI View. It is a different implementation of the problem that was presented in the Implementing a CoreLocation wrapper as @ObservedObject recipe of Chapter 10, Driving SwiftUI with Data.Usually, when a reactive framework is used, instead of the common Model-View-Controller (MVC) pattern used in many iOS apps, people tend to use Model-View-ViewModel (MVVM).In this architectural pattern, the view doesn't have any logic. Instead, this is encapsulated in the intermediate object, the ViewModel, which has the responsibility of being the model for the view and talking to the business logic model, services, and so on to update itself. For example, it will have a property...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
SwiftUI Cookbook - Third Edition
Published in: Dec 2023Publisher: PacktISBN-13: 9781805121732
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Juan C. Catalan

Juan C. Catalan is a software engineer with more than 18 years of professional experience. He started mobile development back in the days of iOS 3. Juan has worked as a professional iOS developer in many industries, including medical devices, financial services, real estate, document management, fleet tracking and industrial automation. He has contributed to more than 30 published apps in the App Store, some of them with millions of users. Juan gives back to the iOS development community with technical talks, mentoring developers, reviewing technical books and now as a book author. He lives in Austin, Texas, with his wife Donna, where they spend time with their kids.
Read more about Juan C. Catalan