Marco Eidinger
Swifty Tech by Marco Eidinger

Swifty Tech by Marco Eidinger

watchOS articles from Apple

Photo by Raagesh C on Unsplash

watchOS articles from Apple

Find your way through Apple's articles and documentation on watchOS development

Marco Eidinger's photo
Marco Eidinger
·Jun 2, 2022·

13 min read

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

The following is a collection of information found on developer.apple.com:

ArticleSummary
watchOS AppsBuild watchOS apps that combine complications, notifications, and SiriKit intents to create a personal experience on Apple Watch.
Setting Up a watchOS Project"Getting Started" article on how to create a new watchOS project or add a watch target to an existing iOS project.
Building a watchOS App"Getting Started" article on how to set up your app’s life cycle and create its user interface using SwiftUI.
Life CyclesReceive and respond to life cycle notifications.
Working with the watchOS App Life CycleLearn how the watchOS app life cycle operates and responds to life cycle notification methods.
Handling Common State TransitionsDetect and respond to common state transitions.
Handling User ActivityDetect and respond to user activity information from Handoff or a complication.
Background ExecutionManage background sessions and tasks.
Using Extended Runtime SessionsCreate an extended runtime session that continues running your app after the user stops interacting with it.
Keeping Your watchOS Content Up to DateEnsure that your app’s content is relevant and up to date.
Watch ConnectivityFramework to implement two-way communication between an iOS app and its paired watchOS app.
Designing Your App for the Always On StateCustomize your watchOS app’s user interface for continuous display.
Taking Advantage of Frontmost App StateUnderstand the frontmost app state, and the features it provides to your app.
Authenticating Users on Apple WatchCreate an account sign-up and sign-in strategy for your app.

What you read next are direct quotes from those articles. I copied essential information and re-arranged them to make better sense of them.

I may also quote information from Apple's Human Interface Guidelines for watchOS and the WatchKit framework documentation.

I encourage you to read the latest article version to be up-to-date.

watchOS Apps

Apple Watch provides easy access to vital information on someone’s wrist. The watchOS experience focuses on quick actions that achieve useful tasks through brief, punctuated interactions.

On Apple Watch, keep interactions as short as possible. Provide vital information at a glance, encouraging the wearer to respond with just a few taps, and then drop their wrist and move on. They don’t need to wait to see if the action succeeds; instead, the watchOS app automatically notifies them of any important updates.

When designing a watchOS app, mix a combination of the following technologies to create a richer experience:

  • The watchOS App: The main app serves as the foundation for the watch experience. Anyone can launch and interact with your app directly. However, the app’s interface isn’t necessarily the primary way people interact with your app. Many may prefer to interact through complications or notifications, and may never explicitly launch your app.

    Noise updates a real-time meter and text descriptions as noise increases or decreases.

  • Complications: Complications provide small glimpses into your app’s data directly on the watch face. People can add complications to most watch faces, but space is limited. Design complications to show information that is timely, up to date, and useful. People can also launch the watchOS app quickly and easily by tapping the complication.

    Complication Example

  • Notifications: Use notifications to alert people of significant events. You can also provide actions so that people can respond immediately without opening your app. You can use either local or remote notifications to communicate, even when your app isn’t running.

    Long Looks example

  • Siri: Use Siri to expand the ways people can interact with your app. With SiriKit Intents, people can control your app with their voice. Similarly, your app can donate shortcuts to the system that appear on the Siri watch face.

    Siri Example

Setting Up a watchOS Project

Xcode divides the watchOS app into two sections:

  • WatchKit App: An app bundle that contains your watchOS app’s storyboard and any assets used by the storyboard.
  • WatchKit Extension: An extension that contains your watchOS app’s code.

Building a watchOS App

On watchOS, SwiftUI gives you considerably more freedom, power, and control than older user interfaces laid out and designed in a storyboard.

To use SwiftUI to manage your app’s life cycle, create a structure that adopts the App protocol in your WatchKit Extension target.

Use an extension delegate to handle the following events:

  • Life cycle events, like applicationDidFinishLaunching(), that aren’t handled by the scenePhase environment variable
  • userInfo dictionaries from either handoff or complications
  • Remote Now Playing activity
  • Workout configurations and recovery
  • Extended runtime sessions
  • Background refresh tasks
  • Registration of remote notifications
@main
struct MyWatchAppApp: App {

    @WKExtensionDelegateAdaptor var extensionDelegate: MyExtensionDelegate

    var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView()
            }
        }
    }
}

Life Cycles

The system reports changes in your app’s execution state to your SwiftUI environment and your extension delegate object. State changes correspond to major events in the lifetime of your app, such as the app launching or moving into the background. Use the state changes to trigger relevant tasks, such as loading shared resources and configuring your initial user interface. The table below shows the possible states and their implications for your app.

StateDescription
Not runningThe watchOS app isn’t running.
InactiveThe watchOS app is running in the foreground, but isn’t receiving actions from controls or gestures.
ActiveThe watchOS app is running in the foreground and receiving actions from controls and gestures. This is the normal mode for apps running on screen.
BackgroundThe system has given the watchOS app a small amount of background execution time.
SuspendedThe app is in memory but isn’t executing code. The system may purge suspended apps at any time to make room for other apps.

When the system receives background data, it may not immediately wake the watchOS app to process that data. Instead, it may delay delivery of the data to preserve battery life.

If the app is currently running—either active and onscreen, or inactive and the frontmost app—the system immediately delivers the data to the app. If the app is in the background, the system wakes the app within 10 minutes to deliver the data.

Handling Common State Transitions

A watchOS app runs in different states depending on the app’s current context. At any time, the app is in one of the following states: not running, inactive, active, background, or suspended. The app changes state over time based on events triggered by the user and the system.

ec07a686-2315-4700-9415-6485cc3bcfff.png

The figure shows the three main types of transitions that occur during an app’s life cycle.

  • Transition A. Launching from not running to either the inactive or background state.
  • Transition B. Switching between the inactive and active states.
  • Transition C. Switching between the background and inactive states.

An app begins in the "not running" state. The user hasn’t launched the watchOS app, or the system suspended and then purged the app from memory.

When the user or the system launches the app, it starts in the inactive state. The app runs in the foreground but isn’t receiving actions from controls or gestures; however, it may be executing other code. A newly launched app usually stays in this state only briefly as it transitions to the active state. When an active app transitions to this state, it should quiet itself and prepare to go to the background.

The app then enters the active state. It runs in the foreground and receiving actions from controls and gestures. This is the normal mode for apps running on screen.

Handling Common State Transitions

SituationApp stateInterface state
Running on screenActiveActive
Running in the dockInactive, and the extension’s isApplicationRunningInDock property is trueActive, shown in the dock
Running as the frontmost appInactiveInactive
Displaying a dynamic notification interfaceInactive or backgroundNotification interface is active
Processing a snapshot background taskBackgroundActive, but not shown on screen
Processing another background taskBackgroundInactive
Running a background sessionBackgroundInactive

Background Execution

Apps on watchOS primarily run in the foreground in order to limit the impact on system resources. However, there are times an app needs to perform an action even when it’s not the foreground app. For a limited number of cases, watchOS provides options for running in the background.

  • Handle Background Notifications
    • Handle background notifications from local or remote notifications
    • Receive push notifications to update your app’s complications
  • Schedule and Handle Background Refresh Tasks
  • Background Sessions (for apps that support workouts, audio playback, or location updates) which can continue to run in the background until the current session ends.
  • Extended Runtime Sessions (for session types Self care, Mindfulness, Physical therapy and Smart alarm)

Keeping Your watchOS Content Up to Date

A watchOS app rarely runs in isolation; it needs data from the outside world. You can access data directly from a web service, CloudKit, or other online resources. You can also share data from a paired iPhone, although this can’t be your app’s primary way of accessing data.

Because Apple Watch has several ways to connect to the internet, it’s important to test all of your app’s networking code over all possible routes.

Access Data Directly

Your watchOS app can connect directly to web services and other online sources. When making these requests, the system can send data through a paired iPhone as a proxy, over a known Wi-Fi network, or over the watch’s own cellular connection

Use CloudKit to Store Data in the Cloud

CloudKit lets you save data in an iCloud container, sharing that data across all the user’s iCloud-connected devices. For example, you could use CloudKit to share your app’s settings or sync the user’s current location in a long-form audio file. CloudKit also lets you create cloud-based apps without having to set up and manage your own servers.

Share Data with the Paired iPhone

If your watchOS app has a companion iOS app installed, you can take advantage of it to update your watchOS app from its companion. For example, if the user’s iPhone and Apple Watch can communicate with each other, use the Watch Connectivity framework to opportunistically send updates from iOS to watchOS.

However, WatchConnectivity isn’t always available. In watchOS 6 and later, users may not install the iOS companion for their independent watchOS apps. Also, with the release of the Apple Watch Series 3 (GPS + Cellular), even dependent apps are likely to be away from the paired iPhone for extended periods. It’s vital that your app continue to provide useful information even when it can’t connect with its companion, so you can’t rely on WatchConnectivity as your only means of updating the watchOS app. Instead, use the WatchConnectivity framework as an opportunistic optimization, rather than the primary means of supplying fresh data.

Watch Connectivity

Use this framework to transfer data between your iOS app and the WatchKit extension of a paired watchOS app (two-way communication).

After initiating a transfer from your app, the system assumes responsibility for the transmission of any data. Most transfers happen in the background when the receiving app is inactive. When the app wakes up, it is notified of any data that arrived while it was inactive. Live communication is also possible when both apps are active.

The Watch Connectivity framework provides APIs to do the following tasks:

  • Update application contexts: use updateApplicationContext(_:) to send a dictionary of data items to the counterpart app. When the counterpart wakes, it can use this information to update its own state. For example, an iOS app that supports Background App Refresh can use part of its background execution time to update the corresponding Watch app. This method overwrites the previous data dictionary, so use this method when your app needs only the most recent data values.
  • Send messages. Use sendMessage(_:replyHandler:errorHandler:) to send a dictionary of data to the counterpart as soon as possible (to a reachable counterpart!). These methods are intended for immediate communication between your iOS app and WatchKit extension.
  • Transfer user info and manage the outstanding transfers: usetransferUserInfo(_:) to send a dictionary of data to the counterpart and ensure that it’s delivered. DOES NOT WORK IN SIMULATOR
  • Transfer files, view transfer progress, and manage the outstanding transfers. Use transferFile(_:metadata:) to transfer files in the background. Use this method in cases where you want to send more than a dictionary of values. DOES NOT WORK IN SIMULATOR
  • Update current complications from iOS apps. Use transferCurrentComplicationUserInfo(_:) to send data related to your Watch app’s complication. Use of this method counts against your complication’s time budget. DOES NOT WORK IN SIMULATOR

Remember that background transfers are not delivered immediately. The system sends data as quickly as possible but transfers are not instantaneous, and the system may delay transfers slightly to improve power usage.

When sending messages, send only the data that your app needs. All transfers involve sending data wireless to the counterpart app, which consumes power. Rather than sending all of your data every time, send only the items that have changed.

Designing Your App for the Always On State

The launch of watchOS 6 introduced the Always On state. Supported devices continued to display the time, even when the user isn’t actively interacting with the watch; however, when running an app, the system blurs the app’s user interface and displays the time over it.

In watchOS 8, Always On expands to include your apps. Apple Watch continues to display your app’s user interface as long as it’s either the frontmost app or running a background session. To preserve battery life, the system updates the user interface at a much lower frequency than when running in the foreground. It also dims the watch.

Even though your app is inactive or running in the background, the system continues to update and monitor many of the user interface elements. For example, when displaying dates and times, using Text.DateStyle values like relative, offset, and timer, the system automatically updates the Text view while in Always On.

Additionally, any controls in the user interface remain interactive. Users can tap buttons, toggle switches, or select items from a list. When the user interacts with a control, the system runs the associated action and transitions your app back to the active state.

IMPORTANT: Always On isn’t available on Apple Watch SE or Apple Watch Series 4 and earlier. For these devices, the screen turns off when the app transitions to the background or inactive states.

Taking Advantage of Frontmost App State

On Apple Watch Series 5 and later, the system blurs the app’s user interface and displays the time over it.

Whether the screen is off or blurred, the app transitions to an inactive state. Its user interface is no longer shown, and it doesn’t receive actions from controls or gestures. However, the app is still in the foreground, and may respond to other events.

An app in this extended, inactive state is the frontmost app. The system can have at most one frontmost app at a time. When the user raises their wrist, the system automatically activates and displays the frontmost app. The frontmost app can perform the following tasks:

  • Play haptic feedback.
  • Receive notifications.
  • Respond immediately to the completion of a background transfer from a task or Watch Connectivity session.
  • Receive up to four background app refresh tasks per hour—similar to an app with a complication on the active watch face.

By default, the frontmost app remains in the foreground for two minutes before transitioning to the background and then becoming suspended. If the user dismisses the app (for example, by pressing the crown or by covering the screen), the app transitions immediately to the background, and doesn’t become the frontmost app.

Users can configure how long apps remain as the frontmost app using Settings > General > Wake Screen.

Authenticating Users on Apple Watch

Users can launch an independent watchOS app as soon as it downloads, even if they don’t have their iPhone. As a result, users must be able to set up the application directly on Apple Watch. If your app requires an account, users must be able to create it and sign in on the watch.

You have the following options for syncing or saving user data:

  1. Create an app that doesn’t require user accounts. Design your app so that it provides a full set of features without user accounts, or use CloudKit to sync and store your user’s data. Apps can access CloudKit data based on the user’s Apple ID without in-app sign-in. watchOS 6 and later also supports CloudKit subscriptions and notifications to let your app respond to changes from other devices.
  2. Authenticate users with Sign In with Apple. This feature authenticates users based on their Apple ID. For more information, see WKInterfaceAuthorizationAppleIDButton and Authentication Services.
  3. Create custom sign-in and sign-up forms.

Did you find this article valuable?

Support Marco Eidinger by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this