iOS进阶+实战selector

iOS16适配指南之Live Activity

2022-12-07  本文已影响0人  YungFan

介绍

准备工作

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

案例

import WidgetKit
import SwiftUI

@main
struct UserSportsBundle: WidgetBundle {
    var body: some Widget {
        // Widget
        UserSports()
        // Live Activity
        UserSportsLiveActivity()
    }
}
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)
        }
    }
}
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<UserSportsAttributes>?

    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<UserSportsAttributes>.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<UserSportsAttributes>.activities {
                await activity.end()
            }
        }
    }
}

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

源代码

Live Activity-Sports

上一篇下一篇

猜你喜欢

热点阅读