iOS Live Activities

Discover iOS Live Activities in our Release Notes video

Overview

Live Activities display your app’s most current data on the iPhone or iPad Lock Screen and in the Dynamic Island. This feature allows users to see live information at a glance and perform quick actions related to the displayed information.

Here are a few examples of using Live Activities:

  • Show order status in a delivery app;

  • Provide a real-time countdown in a training app;

  • Show tracking information in a taxi app;

  • Display game stats and current scores in a sports app;

  • Provide hourly forecasts in a weather app.

You can enable Live Activities using the Pushwoosh iOS SDK as described below. To manage Live Activities and update their content, use the /updateLiveActivity method.

Setup

1. Add a Widget Extension

1.1 Create a new target

Go to File > New > Target and select Widget Extension

1.2 Widget Extension Configuration

Please enter a name and make sure to select 'Include Live Activity' and click Finish

2. Info.plist configuration

Find the Info.plist file in the primary target, insert the "Supports Live Activities" key, and set its value to YES.

3. Enabling Live Activities From App

To enable Live Activities, add their code to your existing widget extension or create a new one if your app doesn’t already have it. Live Activities use SwiftUI and WidgetKit functionality for their user interface. ActivityKit handles the life cycle of each Live Activity: its API is used to request, update, and end a Live Activity and to receive ActivityKit push notifications. You can learn more about Live Activities in the Apple documentation.

3.1 Navigate to the ContentView file of your project in Xcode and create a Button

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(spacing: 20) {
            
            Button(action: {
                LiveActivityManager.shared.startActivity()
            }, label: {
                Text("Start Live Activity")
                    .foregroundColor(.white)
                    .padding() 
                    .background(Color.blue)
                    .cornerRadius(10)
            })
        }
        .padding()
    }
}

#Preview {
    ContentView()
}

3.2 Create a LiveActivityManager.swift file to manage Live Activities

import Foundation
import ActivityKit
import UIKit
import PushwooshFramework

class LiveActivityManager: NSObject, ObservableObject {
    public static let shared: LiveActivityManager = LiveActivityManager()
    
    private var currentActivity: Activity<LiveActivityAttributes>? = nil
    
    override init() {
        super.init()
    }
    
    func startActivity() {
        guard ActivityAuthorizationInfo().areActivitiesEnabled else {
            print("You can't start live activity.")
            return
        }
        do {
            let atttribute = LiveActivityAttributes(name:"Hello, Pushwoosh!")
            let initialState = LiveActivityAttributes.ContentState(emoji: "😇")
            let activity = try Activity<LiveActivityAttributes>.request(
                attributes: atttribute,
                content: .init(state:initialState , staleDate: nil),
                pushType: .token
            )
            self.currentActivity = activity
            
            Task {
                for await pushToken in activity.pushTokenUpdates {
                    let pushTokenString = pushToken.reduce("") {
                        $0 + String(format: "%02x", $1)
                    }
                    print("Activity:\(activity.id) push token: \(pushTokenString)")
                    
                    // MARK: - Send Push Token to Pushwooth
                    do {
                        try await Pushwoosh.sharedInstance().startLiveActivity(withToken: pushTokenString)
                    } catch {
                        print("Error Starting Live Activity: \(error.localizedDescription)")
                    }
                }
            }
        } catch {
            print("Start Activity Error: \(error.localizedDescription)")
        }
    }
}

3.3 That's it, now we run the project and press the 'Start Live Activity' button. Then we navigate to the lock screen and see the created Live Activity.

4. Start Live Activity with a Remote Push Notification

4.1 To initiate a Live Activity via Remote Push Notification, you need to send the pushToStartTokenUpdates token to Pushwoosh.

func getPushToStartToken() {
    if #available(iOS 17.2, *) {
        Task {
            for await data in Activity<LiveActivityAttributes>.pushToStartTokenUpdates {
                let token = data.map {String(format: "%02x", $0)}.joined()
                print("Activity PushToStart Token: \(token)")
                    
                // Send `pushToStartTokenUpdates` token to Pushwoosh
                try await Pushwoosh.sharedInstance().sendPush(toStartLiveActivityToken: token)
            }
        }
    }
}

4.2 Initiate a Live Activity with a Remote Push Notification

Follow our Pushwoosh API reference for instructions and examples on making a request to start a Live Activity remotely.

5. Pushwoosh enables the start and management of Live Activities through Push Notifications.

The Pushwoosh iOS SDK provides the following methods for working with Live Activities:

// Send Live Activity Push To Start Token to Pushwoosh
- (void)sendPushToStartLiveActivityToken:(NSString *_Nullable)token;
- (void)sendPushToStartLiveActivityToken:(NSString *_Nullable)token completion:(void (^ _Nullable)(NSError * _Nullable))completion;

// Start Live Activity Methods with Activity ID
- (void)startLiveActivityWithToken:(NSString * _Nonnull)token activityId:(NSString * _Nullable)activityId;
- (void)startLiveActivityWithToken:(NSString * _Nonnull)token 
                        activityId:(NSString * _Nullable)activityId 
                        completion:(void (^ _Nullable)(NSError * _Nullable error))completion;
                        
- (void)stopLiveActivity;
- (void)stopLiveActivityWithCompletion:(void (^ _Nullable)(NSError * _Nullable error))completion;

When creating a Live Activity from App or via a Remote Push Notification , pass the token to the Pushwoosh server by using the methods below:

- (void)startLiveActivityWithToken:(NSString * _Nonnull)token activityId:(NSString * _Nullable)activityId;
- (void)startLiveActivityWithToken:(NSString * _Nonnull)token 
                        activityId:(NSString * _Nullable)activityId 
                        completion:(void (^ _Nullable)(NSError * _Nullable error))completion;

You can also update live activities by segments using the Activity ID parameter. When creating an activity, you need to pass a unique Activity ID parameter in the method, which will be relevant for a specific user segment.

For example, N users have subscribed to the same event in a live Activity. It is necessary that the Activity ID parameter be unique for all of these N users.

When you finish working with a Live Activity, use these methods:

- (void)stopLiveActivity;
- (void)stopLiveActivityWithCompletion:(void (^ _Nullable)(NSError * _Nullable error))completion;

You can manage iOS Live Activities via Pushwoosh API.

6. Setup()method.

Pushwoosh simplifies the transfer of activity IDs by introducing the PushwooshLiveActivities.setup function, which handles the entire lifecycle of a Live Activity within the application. This function automatically listens for both pushToStart and pushToUpdate token updates. By using this method, the application no longer needs to manually track the initiation of Live Activities or manage token updates for activity updates.

In the AppDelegate, ensure you import PushwooshFramework and call the setup method from the PushwooshLiveActivities class.

AppDelegate.swift

if #available(iOS 16.1, *) {
    PushwooshLiveActivities.setup(DemoAppWidgetAttributes.self)
}
import ActivityKit
import PushwooshFramework

struct DemoAppWidgetAttributes: PushwooshLiveActivityAttributes {
    
    // Nested struct that defines the content state for the live activity.
    public struct ContentState: PushwooshLiveActivityContentState {
        
        var emoji: String
        // Requared property holding data associated with Pushwoosh live activity content.
        var pushwoosh: PushwooshLiveActivityContentStateData?
    }

    var name: String
    // Stores additional Pushwoosh-specific data for the live activity attributes.
    var pushwoosh: PushwooshLiveActivityAttributeData
}

DemoAppWidgetAttributes: This structure conforms to the PushwooshLiveActivityAttributes protocol. It is used to define the attributes of a live activity within the app.

You can manage Live Activities and update their content using the /updateLiveActivity method of the Pushwoosh API. For more information, please read this guide:

Last updated