开发工具:Xcode 功能需要: SwiftUI实现UI页面,iOS16.1以上系统使用
功能使用: 需应用为启动状态
功能说明
iOS16.1 系统支持实时活动功能,可以在锁定屏幕上实时获知各种事情的进展,MobPushSDK iOS 4.0.3版本已完成适配,可根据文档对应使用。
集成步骤
添加依赖库
ActivityKit.farework
SwiftUI.farework
配置⼯程⽀持 LiveActivity
在主⼯程的 Info.plist ⽂件中添加⼀个键值对,key 为 NSSupportsLiveActivities,value 为 YES
添加实时活动扩展
添加扩展项目依赖库
UI实现
实时活动UI需开发者自行实现,可参考Demo处理,注意需将扩展的UI组件引用到主项目上
实时活动API
上传实时活动token registerLiveActivityWithID()
示例代码:
/*!
* @abstract 注册LiveActivity并上报PushToken
* 在PushToken更新时,需同步调用该接口
* 在LiveActivity结束时,需同步调用该接口,PushToken为nil
*
* @param liveActivityId 标识某一个LiveActivity
* @param pushToken 对应LiveActivity的PushToken
* @param handler 结果回调
*/
[MobPush registerLiveActivityWithID:@"mpLiveActivity"
pushToken:token
completion:^(NSError *error) {
if (error) {
NSLog(@"Register LiveActivity Failed: %@", error.localizedDescription);
}
}];
}
活动开始startActivity()
示例代码:
static public func startActivity(pushTokenUpdate:@escaping (Bool, Data?)->Void) {
guard ActivityAuthorizationInfo().areActivitiesEnabled else {
//不可用
pushTokenUpdate(false, nil)
//监听可用状态
// for await enablment in ActivityAuthorizationInfo().activityEnablementUpdates {
// print("Activity AuthorizationInfo change to (enablment)")
// }
return
}
endPreActivity()
let state = HeartNoteLiveActivitsLiveAttributes.ContentState(prograssState: .Car)
let attri = HeartNoteLiveActivitsLiveAttributes(name: "MPLiveActivities")
do {
let current = try Activity.request(attributes: attri, contentState: state, pushType: .token)
Task {
for await tokenData in current.pushTokenUpdates {
//监听token更新 注意线程
pushTokenUpdate(true, tokenData)
}
}
Task {
for await state in current.contentStateUpdates {
//监听state状态 开发者可自行编写回调监听
print("1content state update: tip=(state.prograssState)")
}
}
Task {
//监听activity状态 开发者可自行编写回调监听
for await state in current.activityStateUpdates {
print("activity state update: tip=(state) id:(current.id)")
}
}
} catch(let error) {
print("error=",error)
pushTokenUpdate(false, nil)
}
}
更新Activity状态updateActivityState()
static public func updateActivityState(_ value: Int) {
Task {
guard let current = Activity<HeartNoteLiveActivitsLiveAttributes>.activities.first else {
return
}
let state = HeartNoteLiveActivitsLiveAttributes.ContentState(prograssState: PrograssState(rawValue: value) ?? .Arrived)
let alertConfiguration = AlertConfiguration(title: "Delivery Update ", body: "Delivery Update State to (state.prograssState.rawValue)", sound: .default)
await current.update(using: state, alertConfiguration: alertConfiguration)
}
}
关闭Activity状态endPreActivity()
//建议关闭应用的时候要关闭 不然下次启动就脱离控制了
static public func endPreActivity() {
let activities = Activity<HeartNoteLiveActivitsLiveAttributes>.activities.filter { act in
return act.activityState == .active
}
guard activities.count > 0 else { return }
for item in activities {
Task {
// print("end activity (item.id)")
await item.end(dismissalPolicy:.immediate)
}
}
}
标签:await,iOS,current,state,let,MobPush,error,LiveActivity,SDK
From: https://blog.51cto.com/u_14192352/6960318