watchOS: Complications

Feb 7 2023 · Swift 5.6, watchOS 8.5, Xcode 13

Part 1: Introduction to Complications

06. Update with Background Tasks

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 05. Create Templates for Multiple Families Next episode: 07. Update with Background URL Downloads

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

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

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated 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 need to address one more thing.

Scheduled background tasks

There will be times when you know an update should take place in the future, but the watch likely won’t be running your app during that time.

ExtensionDelegate.swift

We’re starting in a new project to help us examine our update options.

func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {

}
  backgroundTasks.forEach { task in

  }
  backgroundTasks.forEach { task in
    switch task {
    
    }
  }
  backgroundTasks.forEach { task in
    switch task {
    🟩default:
      task.setTaskCompletedWithSnapshot(false)
    }
  }
    switch task {
    🟩case let task as WKApplicationRefreshBackgroundTask:
        
    default:...
    switch task {
    case let task as WKApplicationRefreshBackgroundTask:
    🟩// Perform work
    // Update complication, if needed
    // Schedule next task
    // Mark task completed
        
    default:...

The background worker

So, add a new file, called BackgroundWorker.swift Import WatchKit at the top, along with Foundation.

import Foundation
import WatchKit
final class BackgroundWorker { }
public func perform(_ completion: (Bool) -> Void) {
  // Do your background work here
  completion(true)
}
  public func schedule() { }
  public func schedule(🟩firstTime: Bool = false) {
    let minutes = firstTime ? 1 : 15
    let when = Calendar.current.date(
      byAdding: .minute,
      value: minutes,
      to: Date.now
    )!
    WKExtension
      .shared()
      .scheduleBackgroundRefresh(
        withPreferredDate: when,
        userInfo: nil
      ) { error in
        if let error = error {
          print("Unable to schedule: \(error.localizedDescription)")
        }
      }
  }
}

ExtensionDelegate background task

Switch back to ExtensionDelegate.swift and add a new backgroundWorker property to ExtensionDelegate:

private let backgroundWorker = BackgroundWorker()
  backgroundWorker.perform { updateComplications in
  
  }
    if updateComplications {
      Self.updateActiveComplications()
    }
    backgroundWorker.schedule()
    task.setTaskCompletedWithSnapshot(false)
  }