跪拜 Guibai
← Back to the summary

Build iOS Live Activities on Windows: KXBuild Handles Extensions, Dynamic Island, and APNs Push

How to Develop iOS Live Activities: Writing the Dynamic Island with KXBuild and ActivityKit on Windows

iOS Live Activities use ActivityKit to place an ongoing event on the lock screen and the Dynamic Island, such as food delivery, ride-hailing, or a game score. The approach is to add a widget extension to the app to write the UI, then use ActivityKit inside the app to start, update, and end the activity, and when necessary, have the server push updates through APNs.

This article adds a 'food delivery' Live Activity to the SwiftUI project MyApp: use kxbuild project add-target --type widget-live-activity to add the extension, write the three styles for the lock screen and the Dynamic Island, start, update, and end it within the app, and finally push updates via APNs from the computer, all completed on Windows.

The Live Activity UI lives in the widget extension. It's recommended to first read [Add a desktop widget (WidgetKit) to an iOS app]. The Apple rules mentioned here follow official documentation as of October 2026. This is the KXBuild VSCode plugin. Install it before starting.

How are iOS Live Activities different from widgets?

Both use SwiftUI to write the interface and are placed in the same widget extension, but the update mechanisms are entirely different.

Widget Live Activity
Display location Home screen, lock screen, Today view Lock screen, Dynamic Island, StandBy, paired Apple Watch and Mac
Who updates The system fetches data on a timeline The app updates via ActivityKit, or the server pushes
Duration Always Ends when the event ends; maximum 8 hours
Suitable for Summary info at a glance Ongoing states that change every few minutes
Network access Allowed in the timeline Not allowed; data comes only from the app or pushes

Several limitations to know in advance.

Rule Content
System version ActivityKit starts at iOS 16.1; the ActivityContent syntax used below requires iOS 16.2. The extension added here requires iOS 17 or later
Dynamic Island Only iPhones with a Dynamic Island (iPhone 14 Pro and later) show it; other models show only the lock screen style, appearing as a banner when unlocked
Duration An activity lasts at most 8 hours; the system automatically ends it and removes it from the Dynamic Island. After ending, it can stay on the lock screen for up to 4 more hours, so the lock screen maximum is 12 hours
Data size Immutable and mutable data combined cannot exceed 4 KB; each update and push also respects this
Start timing Generally, start while the app is in the foreground; updates and ending can happen in the background
User switch Users can turn off an app's Live Activities in Settings

Step 1: How to add a Live Activity extension?

Choose one of the following two approaches.

kxbuild project add-target -P .\MyApp.xcodeproj --type widget-live-activity --name MyAppWidget

widget-live-activity adds a widget extension that contains both a regular widget and a Live Activity. The extension's bundle ID is the app's bundle ID with a dot and the lowercase name, here com.example.myapp.myappwidget. The command output prompts you to register an App ID for it. For all types and parameters, see [kxbuild command reference] and [Add Target].

If you already added a widget type extension in a previous article (171), you do not need to add another extension. Add the Live Activity code below to the existing extension, include it in the body of MyAppWidgetBundle.swift, and then enable Supports Live Activities in the next section.

What files are generated after adding the extension?

A MyAppWidget folder appears in the project directory.

File Purpose
MyAppWidgetBundle.swift Extension entry point; lists both the widget and the Live Activity
MyAppWidget.swift Regular widget; can be removed from the bundle if not needed
MyAppWidgetLiveActivity.swift Data definitions and UI for the Live Activity
Info.plist Declares this as a WidgetKit extension
Assets.xcassets Accent and background colors

MyAppWidgetBundle.swift already lists both, so no changes are needed.

@main
struct MyAppWidgetBundle: WidgetBundle {
    var body: some Widget {
        MyAppWidget()
        MyAppWidgetLiveActivity()
    }
}

Step 2: Enable Supports Live Activities

The app must declare NSSupportsLiveActivities as YES in Info.plist; otherwise starting a Live Activity fails.

When using widget-live-activity, the app target's build settings already include INFOPLIST_KEY_NSSupportsLiveActivities = YES. You can search for NSSupportsLiveActivities in the Build Settings page of the [Project Settings Editor].

If your project maintains its own Info.plist (for example, migrated from an older Xcode project), add the following key to the app's Info.plist, or change it with the [Property List Editor].

<key>NSSupportsLiveActivities</key>
<true/>

This key goes in the app's Info.plist, not the extension's.

Step 3: How to define Live Activity data?

Live Activity data is split into two parts, described by a structure conforming to ActivityAttributes.

The app needs this type when starting an activity, and the extension needs it when rendering, so an identical definition must appear in both places. Field names, types, and nested structures must match exactly; the JSON in a push is also parsed according to these field names.

Step 4: How to write the lock screen and Dynamic Island UI?

Replace MyAppWidget/MyAppWidgetLiveActivity.swift with the following.

import ActivityKit
import WidgetKit
import SwiftUI

/// Data for the Live Activity. The app must have an identical definition
struct DeliveryAttributes: ActivityAttributes {
    /// Mutable data: each update or push replaces the entire struct
    public struct ContentState: Codable, Hashable {
        var status: String
        var progress: Double
        var eta: Date
    }

    /// Immutable data: set at launch, cannot be changed later
    var orderNumber: String
    var shopName: String
}

struct MyAppWidgetLiveActivity: Widget {
    var body: some WidgetConfiguration {
        ActivityConfiguration(for: DeliveryAttributes.self) { context in
            // Lock screen, and banner on devices without a Dynamic Island
            DeliveryLockScreenView(context: context)
                .activityBackgroundTint(Color.orange.opacity(0.15))
                .activitySystemActionForegroundColor(.orange)
        } dynamicIsland: { context in
            DynamicIsland {
                // Expanded style: long-press the Dynamic Island, or when an update with alert arrives
                DynamicIslandExpandedRegion(.leading) {
                    Label(context.attributes.shopName, systemImage: "bag.fill")
                        .font(.caption)
                        .foregroundStyle(.orange)
                }
                DynamicIslandExpandedRegion(.trailing) {
                    CountdownText(eta: context.state.eta)
                        .font(.caption.bold())
                }
                DynamicIslandExpandedRegion(.center) {
                    Text(context.state.status)
                        .font(.headline)
                        .lineLimit(1)
                }
                DynamicIslandExpandedRegion(.bottom) {
                    ProgressView(value: context.state.progress)
                        .tint(.orange)
                }
            } compactLeading: {
                Image(systemName: "bag.fill")
                    .foregroundStyle(.orange)
            } compactTrailing: {
                CountdownText(eta: context.state.eta)
                    .frame(width: 44)
                    .font(.caption2.bold())
            } minimal: {
                Image(systemName: "bag.fill")
                    .foregroundStyle(.orange)
            }
            .keylineTint(.orange)
        }
    }
}

struct DeliveryLockScreenView: View {
    let context: ActivityViewContext<DeliveryAttributes>

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Label(context.attributes.shopName, systemImage: "bag.fill")
                    .font(.subheadline.bold())
                    .foregroundStyle(.orange)
                Spacer()
                Text("Order \(context.attributes.orderNumber)")
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
            HStack(alignment: .firstTextBaseline) {
                Text(context.isStale ? "Status may be stale" : context.state.status)
                    .font(.headline)
                Spacer()
                CountdownText(eta: context.state.eta)
                    .font(.headline)
            }
            ProgressView(value: context.state.progress)
                .tint(.orange)
        }
        .padding()
    }
}

/// Countdown is handled by the system; no need to update the Live Activity every second
struct CountdownText: View {
    let eta: Date

    var body: some View {
        if eta > Date() {
            Text(timerInterval: Date()...eta, countsDown: true)
                .monospacedDigit()
                .multilineTextAlignment(.trailing)
        } else {
            Text("Arriving soon")
        }
    }
}

The first closure of ActivityConfiguration is the lock screen style; the dynamicIsland closure contains the three Dynamic Island styles. All three must be provided; the system selects one automatically.

Style When it appears Code location
Compact When only one Live Activity exists, one block on each side of the camera compactLeading, compactTrailing
Minimal When multiple apps have Live Activities, shrinks to a small circle minimal
Expanded Long-press the Dynamic Island, or briefly when an update with alert is received The regions inside DynamicIsland { }

The expanded style uses DynamicIslandExpandedRegion to place content in sections.

Region Position
.leading Left of the camera; stacks downward when content is long
.trailing Right of the camera; stacks downward when content is long
.center Below the camera
.bottom Below the three areas; suitable for a progress bar

Keep these points in mind when writing the UI.

Tapping a Live Activity opens the app by default.

Step 5: How to start, update, and end in the app?

Replace MyApp/ContentView.swift with the following. The file begins with the identical DeliveryAttributes as in the extension, followed by a class managing the Live Activity and three buttons.

import ActivityKit
import SwiftUI

/// Must match the definition in the widget exactly, down to every character
struct DeliveryAttributes: ActivityAttributes {
    public struct ContentState: Codable, Hashable {
        var status: String
        var progress: Double
        var eta: Date
    }

    var orderNumber: String
    var shopName: String
}

@available(iOS 16.2, *)
@MainActor
final class DeliveryActivityManager: ObservableObject {
    @Published var message = ""
    private var activity: Activity<DeliveryAttributes>?

    init() {
        // After the app is terminated by the system and reopened, reconnect to an ongoing Live Activity
        activity = Activity<DeliveryAttributes>.activities.first
    }

    func start() {
        guard ActivityAuthorizationInfo().areActivitiesEnabled else {
            message = "Live Activities are turned off in Settings"
            return
        }
        let attributes = DeliveryAttributes(orderNumber: "A1024", shopName: "Corner Coffee")
        let state = DeliveryAttributes.ContentState(
            status: "Restaurant accepted",
            progress: 0.2,
            eta: Date().addingTimeInterval(20 * 60)
        )
        do {
            let activity = try Activity.request(
                attributes: attributes,
                content: ActivityContent(state: state, staleDate: Date().addingTimeInterval(30 * 60)),
                pushType: .token // Pass nil if you don't use push updates
            )
            self.activity = activity
            message = "Started \(activity.id)"
            watchPushToken(of: activity)
        } catch {
            message = "Start failed: \(error.localizedDescription)"
        }
    }

    func update() async {
        guard let activity else { return }
        let state = DeliveryAttributes.ContentState(
            status: "Rider picked up",
            progress: 0.7,
            eta: Date().addingTimeInterval(8 * 60)
        )
        await activity.update(
            ActivityContent(state: state, staleDate: Date().addingTimeInterval(15 * 60)),
            alertConfiguration: AlertConfiguration(title: "Rider picked up", body: "Estimated delivery in 8 minutes", sound: .default)
        )
        message = "Updated"
    }

    func end() async {
        guard let activity else { return }
        let final = DeliveryAttributes.ContentState(status: "Delivered", progress: 1, eta: Date())
        await activity.end(ActivityContent(state: final, staleDate: nil), dismissalPolicy: .default)
        self.activity = nil
        message = "Ended"
    }

    private func watchPushToken(of activity: Activity<DeliveryAttributes>) {
        Task {
            // Token is generated asynchronously and can change; report every change
            for await data in activity.pushTokenUpdates {
                let token = data.map { String(format: "%02x", $0) }.joined()
                print("Live Activity push token: \(token)")
                // Send the token with the order number to your server here
            }
        }
    }
}

@available(iOS 16.2, *)
struct DeliveryPanel: View {
    @StateObject private var manager = DeliveryActivityManager()

    var body: some View {
        VStack(spacing: 16) {
            Button("Start Delivery") { manager.start() }
                .buttonStyle(.borderedProminent)
            Button("Rider Picked Up") { Task { await manager.update() } }
            Button("Delivered, End") { Task { await manager.end() } }
            Text(manager.message)
                .font(.footnote)
                .foregroundStyle(.secondary)
        }
    }
}

struct ContentView: View {
    var body: some View {
        if #available(iOS 16.2, *) {
            DeliveryPanel()
                .padding()
        } else {
            Text("Live Activities require iOS 16.2 or later")
        }
    }
}

The three actions correspond to three ActivityKit methods.

Action Method Key points
Start Activity.request(attributes:content:pushType:) Call while the app is in the foreground. pushType: .token indicates you will use pushes to update; you receive a push token
Update activity.update(_:alertConfiguration:) Pass a new ContentState. When AlertConfiguration is included, devices with a Dynamic Island briefly expand; other devices show a banner
End activity.end(_:dismissalPolicy:) Include the final state. .default leaves it on the lock screen for a while, .immediate removes it instantly, .after(date) removes it at a specified time

Starting can fail, for example, if the user disabled Live Activities or the device already has the maximum number of concurrent activities. Thus, request must be placed in a do/catch block and the error surfaced to the user. Activity<DeliveryAttributes>.activities returns all ongoing activities for this app, allowing you to reconnect after an app restart.

If you are not doing push updates, change pushType: .token to pushType: nil, and you can skip enabling push capability.

Step 6: How to prepare App IDs and provisioning profiles?

The Live Activity extension is a separate program and signs with its own provisioning profile. Log in to developer.apple.com, go to Certificates, Identifiers & Profiles, and proceed in this order.

  1. Register an App ID for the extension. On the Identifiers page, click the plus sign, choose App IDs → App, select Explicit for Bundle ID, and fill in com.example.myapp.myappwidget.
  2. Enable Push Notifications on the app's App ID. Only needed for push updates; in the app's App ID (com.example.myapp), check Push Notifications under Capabilities and save.
  3. Generate provisioning profiles. Create a Development profile for the extension's App ID. After enabling push on the app, edit the app's existing profile and save it again, then re-download.
  4. Place them in the keychain directory. Put both profiles in KXBuild's keychain directory, deleting the app's old profile. During build, KXBuild automatically assigns the appropriate profile to the app and extension based on bundle ID.

For pushes, also add the aps-environment entitlement to the app, exactly as with ordinary push notifications. Follow the "Add entitlements to the project" section from [Add push notifications to an iOS app]. The Live Activity push token is provided by ActivityKit; the app does not need to call registerForRemoteNotifications to obtain it.

For full signing rules for extensions, see [Signing configuration for iOS app extensions].

Step 7: Verify on an iPhone

  1. Select your iPhone in the status bar and press F5. KXBuild builds, signs, and installs both the app and the extension, then launches the app.
  2. Tap "Start Delivery". Pull down Notification Center or the lock screen to see the lock screen Live Activity. On devices with a Dynamic Island, return to the home screen; icons and a countdown appear on the left and right of the Dynamic Island.
  3. Long-press the Dynamic Island to see the expanded style.
  4. Return to the app and tap "Rider Picked Up"; the Dynamic Island briefly expands with an alert, and the lock screen status and progress update accordingly.
  5. Tap "Delivered, End"; the activity disappears from the Dynamic Island, and the lock screen retains the final state.

Debugging notes.

How to update a Live Activity with APNs?

When the app is not in the foreground, server push is the most reliable update method. The flow is as follows.

  1. The app starts an activity with pushType: .token, obtains the activity-specific push token from pushTokenUpdates, and reports it to the server.
  2. When the order status changes, the server sends an liveactivity type push using that token.
  3. The system wakes the extension and re-renders the UI according to the content-state in the push.

The push token belongs to a single activity and is different from the device token for regular push. A new token must be reported for each new activity. It can also change during the activity's lifetime; the server must replace the old token when a new one arrives.

Request headers

The push request uses the same APNs endpoint and JWT signed with the same .p8 key as regular push, with only three headers different.

Header Value Description
apns-push-type liveactivity Fixed value
apns-topic com.example.myapp.push-type.liveactivity App's bundle ID + .push-type.liveactivity, not the extension's bundle ID
apns-priority 5 or 10 10 delivers immediately and counts toward hourly quota; 5 does not count

The address depends on the environment. A Debug package installed via F5 uses https://api.sandbox.push.apple.com; TestFlight and App Store packages use https://api.push.apple.com. For creating a .p8 key, see article 158's "Creating an APNs Authentication Key".

Request body

{
  "aps": {
    "timestamp": 1792370815,
    "event": "update",
    "content-state": {
      "status": "Rider picked up",
      "progress": 0.7,
      "eta": 814064095
    },
    "stale-date": 1792371715
  }
}
Field Description
timestamp Current time in seconds since 1970. The system shows only the latest update
event update for updates, end for ending
content-state Fields must exactly match ContentState; the system uses default decoding rules, cannot use custom JSON encoding strategies
stale-date Optional; after this time the UI shows a stale state
dismissal-date Optional; only used with end, removes from the lock screen at this time; a past time removes immediately
alert Optional; when present, devices with a Dynamic Island expand, others show a banner

eta is a Date type and is the most common source of errors. The system decodes Date with default rules, expecting seconds since January 1, 2001, not Unix timestamps. On the server, subtract 978307200 from the Unix seconds before filling it. To avoid this difference, change the field to a Double holding a Unix timestamp and convert it in the UI with Date(timeIntervalSince1970:).

Sending a test push from a computer

In the folder used in article 158 (which already has the .p8 key), create la.mjs and modify the four constants at the top. The script uses only Node.js built-in modules and automatically fills in timestamp and the converted eta.

import crypto from 'node:crypto'
import fs from 'node:fs'
import http2 from 'node:http2'

const TEAM_ID = 'ABCDE12345'                      // Team ID
const KEY_ID = 'XYZ1234567'                       // Key ID
const KEY_FILE = 'Auth_Key_XYZ1234567.p8'          // .p8 file
const BUNDLE_ID = 'com.example.myapp'             // App's bundle ID, not the extension's
const HOST = 'https://api.sandbox.push.apple.com' // Debug package installed via F5 goes to dev environment

function makeJwt() {
  const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url')
  const unsigned = b64({ alg: 'ES256', kid: KEY_ID }) + '.' + b64({ iss: TEAM_ID, iat: Math.floor(Date.now() / 1000) })
  const key = crypto.createPrivateKey(fs.readFileSync(KEY_FILE))
  const sig = crypto.sign('sha256', Buffer.from(unsigned), { key, dsaEncoding: 'ieee-p1363' })
  return unsigned + '.' + sig.toString('base64url')
}

const [event, token, status = 'Rider picked up', minutes = '8', progress = '0.7'] = process.argv.slice(2)
if (!['update', 'end'].includes(event) || !token) {
  console.log('Usage: node la.mjs update|end <push token> [status] [remaining minutes] [progress]')
  process.exit(1)
}

const now = Math.floor(Date.now() / 1000)
const aps = {
  timestamp: now,
  event,
  'content-state': {
    status,
    progress: Number(progress),
    // Swift's Date decodes as seconds since 2001-01-01 by default
    eta: now + Number(minutes) * 60 - 978307200,
  },
}
if (event === 'update') aps['stale-date'] = now + 15 * 60
if (event === 'end') aps['dismissal-date'] = now + 60 * 60
const payload = JSON.stringify({ aps })
console.log(payload)

const client = http2.connect(HOST)
client.on('error', (err) => { console.error(err.message); process.exit(1) })
const req = client.request({
  ':method': 'POST',
  ':path': '/3/device/' + token,
  authorization: 'bearer ' + makeJwt(),
  'apns-topic': BUNDLE_ID + '.push-type.liveactivity',
  'apns-push-type': 'liveactivity',
  'apns-priority': '10',
})
let code
let body = ''
req.on('response', (headers) => { code = headers[':status'] })
req.setEncoding('utf8')
req.on('data', (chunk) => { body += chunk })
req.on('end', () => { console.log(code, body); client.close() })
req.end(payload)

In the app, tap "Start Delivery", copy the push token from the KXBuild Console, then lock the phone and run the following command.

node la.mjs update paste_the_push_token "Rider is 1 km away" 3 0.9

A 200 response means APNs accepted the request; within a few seconds the lock screen status, countdown, and progress change. Then run end to finish the activity.

node la.mjs end paste_the_push_token "Delivered" 0 1

For 400 or 403 responses, the reason field explains the cause; refer to "APNs Error Responses" in article 158. The most common issues are using the extension's bundle ID for apns-topic, or sending a Debug package to the production address.

Update frequency

The system sets an hourly quota for each app's Live Activity pushes; the exact number is not public. Pushes with apns-priority: 10 count toward the quota and may be throttled; 5 does not count but delivery is less immediate.

Pushes may fail due to no network, and pushes arriving after the activity ends are ignored. When the app returns to the foreground, sync once with update to avoid displaying stale information.

Starting an activity via push

On iOS 17.1 and earlier, pushes can only update and end a Live Activity, not start one.

On newer systems, the app can obtain a start token from Activity<DeliveryAttributes>.pushToStartTokenUpdates. The server uses it to send a push with event as start; the request body must include attributes-type (here DeliveryAttributes), attributes, and alert. Add this after the basic flow is working.

Live Activity not displaying or errors? Troubleshoot

Symptom Cause Resolution
Activity.request throws an error saying unsupported or unauthorized App's Info.plist lacks NSSupportsLiveActivities, or the user disabled Live Activities Check build settings as above; enable Live Activities for the app in Settings
Starts successfully but nothing appears on lock screen or Dynamic Island Extension not installed, or device system is below the iOS 17 requirement Confirm F5 also signed the extension; device runs iOS 17 or later
Only lock screen style, no Dynamic Island Device has no Dynamic Island Normal; test on a device with a Dynamic Island
Start fails with a limit reached error Too many concurrent activities End old activities; request must handle errors
Can't get a push token after waiting App lacks push capability or aps-environment entitlement Enable Push Notifications, regenerate provisioning profile, add entitlement
Push returns 200 but UI unchanged content-state field names or types don't match ContentState, or Date was filled with Unix seconds Check each field; Date uses seconds since 2001
Push returns 400 TopicDisallowed or DeviceTokenNotForTopic apns-topic is wrong, or token and environment don't match Topic is app's bundle ID + .push-type.liveactivity; Debug package uses sandbox address
Build errors about missing extension provisioning profile keychain lacks a profile for com.example.myapp.myappwidget Register App ID and generate profile, place it in keychain
Activity disappears after a few hours Reached the 8-hour limit Normal; split long events into multiple activities or use push notifications

For signing and installation errors, see [16 common signing and ipa installation errors and solutions].

Packaging an app with a Live Activity for distribution

For release, both the app and the extension need App Store provisioning profiles. Put them in the keychain directory, then in the KXBuild view switch to Release in Build Configuration, and run KXBuild: Build from the command palette, or execute the following command.

kxbuild build .\MyApp.xcodeproj -c Release

The generated build\MyApp.ipa already includes the iOS Live Activity extension. For production, send pushes to https://api.push.apple.com, sign the JWT with a Production .p8 key, and use the new token reported by the release build. The extension and app version numbers must match; change them together in the [Project Settings Editor] for both MyApp and MyAppWidget.

FAQ

What is the minimum iOS version for Live Activities?

ActivityKit is available from iOS 16.1. The ActivityContent syntax used here requires iOS 16.2. The extension added by KXBuild requires iOS 17 or later, so the Live Activity described in this article displays on iPhones with iOS 17 or later.

What is the maximum display duration for a Live Activity?

A Live Activity lasts at most 8 hours, after which the system ends it and removes it from the Dynamic Island. After ending, it can stay on the lock screen for up to 4 more hours, so the lock screen maximum is 12 hours.

Can iPhones without a Dynamic Island use Live Activities?

Yes. Devices without a Dynamic Island show the lock screen style; when unlocked, updates with alerts appear as a banner. The Dynamic Island style appears only on iPhones that have it (Pro models from iPhone 14 Pro onward).

How should the apns-topic for Live Activity pushes be written?

Write the app's bundle ID plus .push-type.liveactivity, for example com.example.myapp.push-type.liveactivity, and set apns-push-type to liveactivity. Do not use the extension's bundle ID; use the activity token obtained from pushTokenUpdates.

Push returns 200 but the Live Activity hasn't updated?

Most likely the content-state field names or types don't match ContentState, so the system fails to decode and does not update. Date fields must be filled with seconds since January 1, 2001; timestamp must be the current time; pushes arriving after the activity has ended are also ignored.