苹果在 WWDC22 中,提出了实时活动(Live Activity)的概念,以便于用户在锁屏查看一些应用实时活动的更新。并且ActivityKit实现了灵动岛视图的自定义。经过我近两个月的学习,总结出了一些经验分享出来供大家批评和指正。
iOS16.1 锁屏界面上新增了实时活动界面,目前仅有iPhone 14 Pro和iPhone 14 Pro Max 两款机型上拥有灵动岛。实时活动包括了锁屏界面和灵动岛界面两个部分的内容,示例如下图所示:
相较于iOS16.0的锁屏小组件,实时活动是显示在通知区域,且拥有更自由的视图定制和刷新方式。和小组件一样,它也限制了视图上的动画效果显示。我们可以使用实时更新来做一些有意思的设计和功能。例如上面演示的 运动监测、订单进度、赛事成绩等。
需要在主程序的Info.plist中添加键值:Supports Live Activities为YES
如果项目中已经有WidgetExtension,可以直接快进到第二步。
struct LiveActivitiesWidget: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: LiveActivitiesAttributes.self) {
context in
Text("锁屏上的界面")
.activityBackgroundTint(Color.cyan) // 背景色
.activitySystemActionForegroundColor(Color.black) // 系统操作的按钮字体色
} dynamicIsland: {
context in
DynamicIsland {
DynamicIslandExpandedRegion(.leading) {
Text("灵动岛展开后的左边")
}
DynamicIslandExpandedRegion(.trailing) {
Text("灵动岛展开后的右边")
}
DynamicIslandExpandedRegion(.center) {
Text("灵动岛展开后的中心")
}
DynamicIslandExpandedRegion(.bottom) {
Text("灵动岛展开后的底部")
}
} compactLeading: {
Text("灵动岛未展开的左边")
} compactTrailing: {
Text("灵动岛未展开的右边")
} minimal: {
// 这里是灵动岛有多个任务的情况下,展示优先级高的任务,位置在右边的一个圆圈区域
Text("灵动岛Mini")
}
.widgetURL(URL(string: "http://www.apple.com")) // 点击整个区域,通过deeplink将数据传递给主工程,做相应的业务
.keylineTint(Color.red) // ///设置“动态岛”中显示的“活动”的关键帧线色调。
}
}
}
界面的相关设计规范请参考人机交互官方文档,参考文献3
struct ActivityWidgetAttributes: ActivityAttributes {
public struct ContentState: Codable, Hashable {
var nickname: String // 用户对象的昵称
......
}
// Fixed non-changing properties about your activity go here!
var name: String
}
数据由ContentState(可变部分) 和 不可变部分组成。更新所需要传递的就是可变部分的内容。
实时活动的开启、更新和结束都需要在主程序进行管理。
// 使用方法
public static func request(attributes: Attributes, contentState: Activity<Attributes>.ContentState, pushType: PushType? = nil) throws -> Activity<Attributes>
--------------------------
private var myActivity: Activity<ActivityWidgetAttributes>? = nil
let initialContentState = ActivityWidgetAttributes.ContentState(nickName: "哈哈哈")
let activityAttributes = ActivityWidgetAttributes(name: "嘻嘻嘻")
do {
// 本地更新的创建方式
myActivity = try Activity.request(attributes: activityAttributes, contentState: initialContentState)
// 通知更新的创建方式,需要传递pushType: .token
myActivity = try Activity.request(attributes: activityAttributes, contentState: initialContentState, pushType: .token)
print("Activity id : \(String(describing: cymActivity?.id ?? "nil")).")
} catch (let error) {
print("ActivityError: \(error.localizedDescription)" )
}
// 使用方法
public func update(using contentState: Activity<Attributes>.ContentState, alertConfiguration: AlertConfiguration? = nil) async
------------------------------------------------------------
// 更新内容
let updateStatus = ActivityWidgetAttributes.ContentState(nickName: "啊啊啊")
// 关于通知的配置
let alertConfiguration = AlertConfiguration(title: "111", body: "2222", sound: .default)
Task {
await myActivity?.update(using: updateStatus, alertConfiguration: alertConfiguration)
}
// 使用方法
public func end(using contentState: Activity<Attributes>.ContentState? = nil, dismissalPolicy: ActivityUIDismissalPolicy = .default) async
// 结束策略有3种
/// The system's default dismissal policy for the Live Activity.
///
/// With the default dismissal policy, the system keeps a Live Activity that ended on the Lock Screen for
/// up to four hours after it ends or the user removes it. The ``ActivityKit/ActivityState``
/// doesn't change to ``ActivityKit/ActivityState/dismissed`` until the user or the system
/// removes the Live Activity user interface.
public static let `default`: ActivityUIDismissalPolicy
/// The system immediately removes the Live Activity that ended.
///
/// With the `immediate` dismissal policy, the system immediately removes the ended Live Activity
/// and the ``ActivityKit/ActivityState`` changes to
/// ``ActivityKit/ActivityState/dismissed``.
public static let immediate: ActivityUIDismissalPolicy
/// The system removes the Live Activity that ended at the specified time within a four-hour window.
///
/// Provide a date to tell the system when it should remove a Live Activity that ended. While you can
/// provide any date, the system removes a Live Activity that ended after the specified date or after four
/// hours from the moment the Live Activity ended — whichever comes first. When the system
/// removes the Live Activity, the ``ActivityKit/ActivityState`` changes to ``ActivityKit/ActivityState/dismissed``.
///
/// - Parameters:
/// - date: A date within a four-hour window from the moment the Live Activity ends.
public static func after(_ date: Date) -> ActivityUIDismissalPolicy
--------------------------------------------------------------
Task {
await myActivity?.end(using:nil, dismissalPolicy: .immediate)
}
创建成功后可以使用activityStateUpdates监听到实时活动的状态
Task.detached {
for awaitactivity in Activity<ActivityWidgetAttributes>.activities {
for await state in activity.activityStateUpdates {
if (state == .active) {
/// The Live Activity is active, visible to the user, and can receive content updates.
} else if (state == .ended) {
/// The Live Activity is visible, but the user, app, or system ended it, and it won't update its content anymore.
} else {
// .dismissed
/// The Live Activity ended and is no longer visible because the user or the system removed it.
}
}
}
}
如果需要使用通知进行更新,需要将PushToken发送给服务端。
// 创建时需要 pushType: .token
Activity.request(attributes: activityAttributes, contentState: initialContentState, pushType: .token)
// 创建成功后
Task.detached {
for await activity in Activity<ActivityWidgetAttributes>.activities {
for await pushToken in activitie.pushTokenUpdates {
let mytoken = pushToken.map {
String(format: "%02x", $0)}.joined().uppercased()
// pushToken 是Data 需要经过上面的方法 转换成String传递给服务端使用
print("push token", mytoken)
}
}
}
}
实时活动的权限无法监听获得,只能主动进行判断,需要在进行创建前进行判断来提示用户
// 实时活动是否可用,包括权限是否开启和手机是否支持实时活动
ActivityAuthorizationInfo().areActivitiesEnabled
// 获取已有的实时活动个数
Activity<ActivityWidgetAttributes>.activities.count
服务端需要使用p8 + jwt实现liveActivity的推送
// 推送配置
TEAM_ID=开发者账号里的TEAM_ID
AUTH_KEY_ID=p8推送需要的验证秘钥ID
TOPIC=主程序的Bundle Identifier.push-type.liveactivity
DEVICE_TOKEN=PushToken
APNS_HOST_NAME=api.sandbox.push.apple.com
// APS结构
{
"aps": {
"timestamp":1666667682, // 更新的时间
"event": "update", // 事件选择更新,也可以进行结束操作
"content-state": {
// 需要与程序中的数据结构保持一致
"nickname": "我来更新"
},
"alert": {
// 通知配置
"title": "Track Update",
"body": "Tony Stark is now handling the delivery!"
}
}}
实时活动的网络研讨会上自由提问时间里一些开发者的问题和回答
Q:可以在didBecomeBackground的时刻启动LiveActivity吗?
A:有可能不成功,因为进入后台可能会导致无法取到PushToken
Q:灵动岛是否支持lottie svgs gif等动画吗
A:不行,自定义动画都不支持,系统会处理动画
Q:灵动岛如何进行调试,打断点调试无效
A:暂时无法回答
Q:可以使用ObjC实现实时活动吗
A:不行!ActivityKit Only Swift,需要进行桥接
Q:如何在Live Activity中获取WebImage
A:一次更新不能超过4KB,webimage最好下载好放在本地的
Q:是否可以创建一个Button处理点击事件,而不是打开App
A:不行,通过Link和widgetURL,点击就会自动打开你的App
Q:如果用户没有开启APP的推送权限,会导致无法实施实时活动吗
A:不会,通知推送和实时活动的推送是两套不同的系统,只要实时活动权限开启即可
Q:灵动岛和实时活动一样最多显示8小时吗
A:是的
本人新手,如果有写错的地方欢迎指正,期待和大家一起交流开发。
1.《盒马 iOS Live Activity &“灵动岛”配送场景实践》
2.《iOS灵动岛开发实践》
3.《Apple Developer-Design-Live Activities》
4.《iOS 使用推送通知更新 Dynamic Island 和 Live Activity》
5.《Mastering Dynamic Island in SwiftUI》
产品要求:将用户头像和一些数据显示在实时活动和灵动岛上,随即使用AppGroup保存头像,在创建实时活动时取出头像使用,但是发生了一个很严重的问题。
测试员使用四台手机 iPhone 12、iPhone X、iPhone XR、iPhone 11(iOS版本全部为 16.1.1)进行了测试,iPhone 12、iPhone X成功的显示了实时活动,但是iPhone XR、iPhone 11却没有显示,在Log中发现实时活动虽然被创建了,但是立马被系统删除了。
经过一下午的实验,终于发现
// 主程序保存头像
NSURL *imageURL = [NSURL URLWithString:@"https://xxxxxxxxxxxx.png"];
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:imageURL completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
if (finished && image) {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *pathURL = [fileManager containerURLForSecurityApplicationGroupIdentifier:@"group.app.???.???"];
pathURL = [pathURL URLByAppendingPathComponent:@"ActivityLoverAvatar.png"];
NSData *imageData = UIImagePNGRepresentation(image);
BOOL success = [imageData writeToURL:pathURL atomically:YES];
...
// 创建实时活动
} else {
...
// 处理错误
}
}];
// 实时活动获取对象头像
func getLoveryAvatatImage()->Image {
let manager = FileManager.default
let floderURL:URL = manager.containerURL(forSecurityApplicationGroupIdentifier: "group.app.???.???")!
let fileURL:URL = floderURL.appendingPathComponent("ActivityLoverAvatar.png")
do {
let data: Data = try Data.init(contentsOf: fileURL)
let image = UIImage.init(data: data)
return Image(uiImage: image!)
} catch let error{
print(error.localizedDescription)
return Image("placeholderImage")
}
}
// 实时活动Widget配置
struct ActivityWidget: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: ActivityWidgetAttributes.self) {
context in
ActivityWidgetMainView(context: context) // 内部使用了 getLoveryAvatatImage()
} dynamicIsland: {
context in
DynamicIsland {
// Expanded UI goes here. Compose the expanded UI through
// various regions, like leading/trailing/center/bottom
DynamicIslandExpandedRegion(.leading, priority: 1) {
ActivityWidgetMainDynamicIslandView(context: context) //内部使用了 getLoveryAvatatImage()
.dynamicIsland(verticalPlacement: .belowIfTooWide)
.padding(0)
}
} compactLeading: {
getLoveryAvatatImage()
.resizable()
.frame(width: 22, height: 22)
.clipShape(Circle())
} compactTrailing: {
Image(getIconImageName(context.state.iconName))
.resizable()
.frame(width: 17, height: 17)
} minimal: {
getLoveryAvatatImage()
.resizable()
.frame(width: 22, height: 22)
.clipShape(Circle())
}
}
}
}
代码中一共有4处使用了 getLoveryAvatatImage() 方法,如果删除minimal和compactLeading中的getLoveryAvatatImage(),不能正常显示的两个手机就可以正常显示了。所以,建议设计师将这两处换成了显示App的Logo图片了。
// 实时活动Widget配置
struct ActivityWidget: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: ActivityWidgetAttributes.self) {
context in
ActivityWidgetMainView(context: context) // 内部使用了 getLoveryAvatatImage()
} dynamicIsland: {
context in
DynamicIsland {
// Expanded UI goes here. Compose the expanded UI through
// various regions, like leading/trailing/center/bottom
DynamicIslandExpandedRegion(.leading, priority: 1) {
ActivityWidgetMainDynamicIslandView(context: context) //内部使用了 getLoveryAvatatImage()
.dynamicIsland(verticalPlacement: .belowIfTooWide)
.padding(0)
}
} compactLeading: {
Image("AppLogo")
.resizable()
.frame(width: 22, height: 22)
.clipShape(Circle())
} compactTrailing: {
Image(getIconImageName(context.state.iconName))
.resizable()
.frame(width: 17, height: 17)
} minimal: {
Image("AppLogo")
.resizable()
.frame(width: 22, height: 22)
.clipShape(Circle())
}
}
}
}
但是这个问题的根本原因却不知道,因为有的手机是可以正常使用的,只有那两台测试机无法正常使用。如果有人知道为什么请私信我,大家一起讨论,谢谢!!!
文章浏览阅读2.5w次,点赞6次,收藏50次。官方解释是,docker 容器是机器上的沙盒进程,它与主机上的所有其他进程隔离。所以容器只是操作系统中被隔离开来的一个进程,所谓的容器化,其实也只是对操作系统进行欺骗的一种语法糖。_docker菜鸟教程
文章浏览阅读5.7k次,点赞3次,收藏14次。该如何避免的,今天小编给大家推荐两个下载Windows系统官方软件的资源网站,可以杜绝软件捆绑等行为。该站提供了丰富的Windows官方技术资源,比较重要的有MSDN技术资源文档库、官方工具和资源、应用程序、开发人员工具(Visual Studio 、SQLServer等等)、系统镜像、设计人员工具等。总的来说,这两个都是非常优秀的Windows系统镜像资源站,提供了丰富的Windows系统镜像资源,并且保证了资源的纯净和安全性,有需要的朋友可以去了解一下。这个非常实用的资源网站的创建者是国内的一个网友。_msdn我告诉你
文章浏览阅读1.2k次。vue2封装对话框el-dialog组件_
文章浏览阅读4.7k次,点赞5次,收藏6次。MFC 文本框换行 标签: it mfc 文本框1.将Multiline属性设置为True2.换行是使用"\r\n" (宽字符串为L"\r\n")3.如果需要编辑并且按Enter键换行,还要将 Want Return 设置为 True4.如果需要垂直滚动条的话将Vertical Scroll属性设置为True,需要水平滚动条的话将Horizontal Scroll属性设_c++ mfc同一框内输入二行怎么换行
文章浏览阅读832次。检查Linux是否是否开启所需端口,默认为6379,若未打开,将其开启:以root用户执行iptables -I INPUT -p tcp --dport 6379 -j ACCEPT如果还是未能解决,修改redis.conf,修改主机地址:bind 192.168.85.**;然后使用该配置文件,重新启动Redis服务./redis-server redis.conf..._redis-server doesn't support auth command or ismisconfigured. try
文章浏览阅读4.9k次。济大数电实验报告_数据选择器及其应用
文章浏览阅读236次。1研究内容消费在生产中占据十分重要的地位,是生产的最终目的和动力,是保持省内经济稳定快速发展的核心要素。预测河南省社会消费品零售总额,是进行宏观经济调控和消费体制改变创新的基础,是河南省内人民对美好的全面和谐社会的追求的要求,保持河南省经济稳定和可持续发展具有重要意义。本文建立灰色预测模型,利用MATLAB软件,预测出2019年~2023年河南省社会消费品零售总额预测值分别为21881...._灰色预测模型用什么软件
文章浏览阅读1.2k次。12.4-在Qt中使用Log4Qt输出Log文件,看这一篇就足够了一、为啥要使用第三方Log库,而不用平台自带的Log库二、Log4j系列库的功能介绍与基本概念三、Log4Qt库的基本介绍四、将Log4qt组装成为一个单独模块五、使用配置文件的方式配置Log4Qt六、使用代码的方式配置Log4Qt七、在Qt工程中引入Log4Qt库模块的方法八、获取示例中的源代码一、为啥要使用第三方Log库,而不用平台自带的Log库首先要说明的是,在平时开发和调试中开发平台自带的“打印输出”已经足够了。但_log4qt
文章浏览阅读786次。全局观思维模型,一个教我们由点到线,由线到面,再由面到体,不断的放大格局去思考问题的思维模型。_计算机中对于全局观的
文章浏览阅读330次。一、CountDownLatch介绍CountDownLatch采用减法计算;是一个同步辅助工具类和CyclicBarrier类功能类似,允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。二、CountDownLatch俩种应用场景: 场景一:所有线程在等待开始信号(startSignal.await()),主流程发出开始信号通知,既执行startSignal.countDown()方法后;所有线程才开始执行;每个线程执行完发出做完信号,既执行do..._countdownluach于cyclicbarrier的用法
文章浏览阅读508次。Prometheus 算是一个全能型选手,原生支持容器监控,当然监控传统应用也不是吃干饭的,所以就是容器和非容器他都支持,所有的监控系统都具备这个流程,_-自动化监控系统prometheus&grafana实战
文章浏览阅读4.7k次。输入关键字,可以通过键盘的搜索按钮完成搜索功能。_react search