Chapters

Hide chapters

watchOS With SwiftUI by Tutorials

Second Edition · watchOS 9 · Swift 5.8 · Xcode 14.3

Section I: watchOS With SwiftUI

Section 1: 13 chapters
Show chapters Hide chapters

9. Keeping Complications Updated
Written by Scott Grosch

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Now that your complications are available to place on the watch face, you have one last consideration. How do you ensure the displayed data is up to date?

Background Download

When your complication’s timeline runs out of data, or even before, you’ll want to initiate a background download. While your first instinct is likely to call one of the dataTask methods from URLSession, that won’t work. watchOS might pause and restart your widget extension multiple times during the download. Instead, you’ll have to create a download task.

Refactor CoOpsApi

Now that both the app and the widget extension need to download data, you’ll need to move some files from TideWatch Watch App into Shared. The main file you need is CoOpsApi, but moving it has a cascading effect. Move the CurrentTideKeys file, as well as the Download and Extensions folders into Shared.

Caching Sessions

Apple’s developer documentation specifies, in a complicated manner, that you must reuse sessions when possible. Also, you need to reattach any previously interrupted sessions that have started again.

Timeline Provider

It’s time to initiate a download. Head back to Provider and replace the entire contents of getTimeLine(for:in:completion:) with the following code:

Completing the Session

In SessionCache, when the delegate methods are complete, you’ll need to call the downloadCompletion delegate, if it’s set. Note that even if the session completed with an error, you still need to call the delegate to tell watchOS to complete the timeline. Add a new method, as shown below:

Background URLSession Events

Background network requests are delivered directly to the widget extension, not the containing app. When a background URL session event occurs, you must tell watchOS whether you’re able to process the event, and if so, what to do.

Key Points

  • Always use a data download, not a data task.
  • Ensure you call both the session event’s completion handler as well as the timeline provider’s completion handler.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now