iOS16适配指南之Live Activity

介绍

  • 一种显示在锁屏界面的特殊 Widget,但官方强调 Live Activity 与 Widget 并不完全相等,因为二者使用不同的机制进行更新。
  • 可以通过 ActivityKit 来配置、启动、更新与终止 Live Activity,也可以通过远程通知更新 Live Activity,但二者在更新时的动态数据大小均不能超过 4 KB
  • Live Activity 在锁屏上最多只能停留 12 小时,超过时间会自动停止运行。
  • 开启 Live Activity 后,App 可以与 DynamicIsland 进行动态交互。
  • 仅支持 iPhone,且要求 iOS 16.1 及以上

准备工作

  1. 主项目的 Info.plist 文件中增加字段NSSupportsLiveActivities,将其类型设置为Boolean,值为YES
  2. 添加 Widget 扩展,此时扩展的主目录会产生 3 个源文件,分别为WidgetBundleWidgetLive Activity
  3. 在对应源文件中分别开发WidgetLive Activity
  4. 如果需要远程通知更新,还需要进行远程通知的相关配置。

案例

  • WidgetBundle源文件:配置 Widget 与 Live Activity。
import WidgetKit
import SwiftUI

@main
struct UserSportsBundle: WidgetBundle {
    var body: some Widget {
        // Widget
        UserSports()
        // Live Activity
        UserSportsLiveActivity()
    }
}
  • Live Activity源文件:创建并且配置ActivityAttributes,在Widget中设置锁屏界面与解锁后 App 退到后台时 DynamicIsland 显示的内容。
import ActivityKit
import SwiftUI
import WidgetKit

// MARK:- ActivityAttributes,需要共享给App与Widget
struct UserSportsAttributes: ActivityAttributes {
    public struct ContentState: Codable, Hashable {
        // ContentState需要的属性,可以实时更新
        let amount: Double
    }
    var date: Date
    let name: String
}

// MARK:- SwiftUI View
struct SportActivityView: View {
    let name: String
    let startDate: Date
    var endDate: Date {
        startDate.addingTimeInterval(60)
    }
    let amount: Double

    var body: some View {
        HStack(spacing: 20) {
            ProgressView(timerInterval: startDate ... endDate) {
                let total = String(format: "%.1f", amount)
                Text("本次\(name) \(total) m")
                    .font(.system(size: 17))
            }
            .tint(.green)

            Image(systemName: "figure.run")
                .foregroundStyle(.green)
        }
        .foregroundStyle(.white)
        .padding()
        .activityBackgroundTint(Color.purple.opacity(0.5)) // 背景色
    }
}

// MARK:- Live Activity
struct UserSportsLiveActivity: Widget {
    var body: some WidgetConfiguration {
        ActivityConfiguration(for: UserSportsAttributes.self) { context in
            // 锁屏时显示的内容
            SportActivityView(name: context.attributes.name,
                              startDate: context.attributes.date,
                              amount: context.state.amount)
        } dynamicIsland: { context in
            // DynamicIsland展开后的显示内容
            DynamicIsland {
                DynamicIslandExpandedRegion(.leading) {
                    ZStack {
                        Color.red
                        
                        Text("Leading")
                    }
                }
                DynamicIslandExpandedRegion(.center) {
                    ZStack {
                        Color.green
                        
                        Text(context.attributes.name)
                    }
                }
                DynamicIslandExpandedRegion(.trailing) {
                    ZStack {
                        Color.blue
                        
                        Text("Trailing")
                    }
                }
                DynamicIslandExpandedRegion(.bottom) {
                    ZStack {
                        Color.purple
                        
                        Text("\(context.state.amount)")
                    }
                }
            } compactLeading: {
                Text("Le")
            } compactTrailing: {
                Text("Tr")
            } minimal: {
                Text("Min")
            }
            .widgetURL(URL(string: "https://developer.apple.com"))
            .keylineTint(Color.red)
        }
    }
}
  • 主项目源文件:配置、启动、更新与终止 Live Activity。
import ActivityKit
import Combine
import SwiftUI

struct ContentView: View {
    // 运动量,用于更新Activity的数据
    @State private var amount: Double = 0
    @State private var count = 60
    // 定时器
    @State private var timerPublisher = Timer.publish(every: 5, on: .main, in: .common)
    @State private var timer: Cancellable?
    // Activity
    @State private var activity: Activity?

    func setup() {
        amount = 0
        count = 60
        timerPublisher = Timer.publish(every: 5, on: .main, in: .common)
        timer = timerPublisher.connect()
    }

    var body: some View {
        VStack(spacing: 20) {
            Button("启动") {
                setup()
                let attributes = UserSportsAttributes(date: .now, name: "跑步")         
                let contentState = UserSportsAttributes.ContentState(amount: amount)
                do {
                    activity = try Activity.request(attributes: attributes,
                                                                          contentState: contentState,
                                                                          pushType: nil)
                } catch {
                    print(error.localizedDescription)
                }
            }

            Button("重置") {
                amount = 0
                let contentState = UserSportsAttributes.ContentState(amount: amount)
                Task {
                    await self.activity?.update(using: contentState)
                }
            }

            Button("结束") {
                timer?.cancel()
                Task {
                    await self.activity?.end(using: nil, dismissalPolicy: .immediate)
                }
            }
        }
        .onReceive(timerPublisher) { _ in
            count -= 5
            if count == 0 {
                timer?.cancel()
            }
            amount += Double.random(in: 2.5 ... 25.0)
            let contentState = UserSportsAttributes.ContentState(amount: amount)
            Task {
                await self.activity?.update(using: contentState)
            }
        }
        .task {
            for activity in Activity.activities {
                await activity.end()
            }
        }
    }
}

注意:锁屏状态下执行 Timer 需要打开后台模式。通过 Timer 所在项目的 Signing&Capabilities 添加 Capability,找到并且开启 Background Modes,然后在 Background Modes 中勾选 Audio, AirPlay, and Picture in Picture

源代码

Live Activity-Sports

你可能感兴趣的:(iOS16适配指南之Live Activity)