苹果在 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())
}
}
}
}
但是这个问题的根本原因却不知道,因为有的手机是可以正常使用的,只有那两台测试机无法正常使用。如果有人知道为什么请私信我,大家一起讨论,谢谢!!!
文章浏览阅读3.2k次。本文研究全球与中国市场分布式光纤传感器的发展现状及未来发展趋势,分别从生产和消费的角度分析分布式光纤传感器的主要生产地区、主要消费地区以及主要的生产商。重点分析全球与中国市场的主要厂商产品特点、产品规格、不同规格产品的价格、产量、产值及全球和中国市场主要生产商的市场份额。主要生产商包括:FISO TechnologiesBrugg KabelSensor HighwayOmnisensAFL GlobalQinetiQ GroupLockheed MartinOSENSA Innovati_预计2026年中国分布式传感器市场规模有多大
文章浏览阅读1.1k次,点赞2次,收藏12次。常用组合逻辑电路结构——为IC设计的延时估计铺垫学习目的:估计模块间的delay,确保写的代码的timing 综合能给到多少HZ,以满足需求!_基4布斯算法代码
文章浏览阅读3.3k次,点赞3次,收藏5次。OpenAI Manager助手(基于SpringBoot和Vue)_chatgpt网页版
文章浏览阅读2.2k次。USACO自1992年举办,到目前为止已经举办了27届,目的是为了帮助美国信息学国家队选拔IOI的队员,目前逐渐发展为全球热门的线上赛事,成为美国大学申请条件下,含金量相当高的官方竞赛。USACO的比赛成绩可以助力计算机专业留学,越来越多的学生进入了康奈尔,麻省理工,普林斯顿,哈佛和耶鲁等大学,这些同学的共同点是他们都参加了美国计算机科学竞赛(USACO),并且取得过非常好的成绩。适合参赛人群USACO适合国内在读学生有意向申请美国大学的或者想锻炼自己编程能力的同学,高三学生也可以参加12月的第_usaco可以多次提交吗
文章浏览阅读394次。1.1 存储程序1.2 创建存储过程1.3 创建自定义函数1.3.1 示例1.4 自定义函数和存储过程的区别1.5 变量的使用1.6 定义条件和处理程序1.6.1 定义条件1.6.1.1 示例1.6.2 定义处理程序1.6.2.1 示例1.7 光标的使用1.7.1 声明光标1.7.2 打开光标1.7.3 使用光标1.7.4 关闭光标1.8 流程控制的使用1.8.1 IF语句1.8.2 CASE语句1.8.3 LOOP语句1.8.4 LEAVE语句1.8.5 ITERATE语句1.8.6 REPEAT语句。_mysql自定义函数和存储过程
文章浏览阅读188次。半导体二极管——集成电路最小组成单元。_本征半导体电流为0
文章浏览阅读2.8k次,点赞3次,收藏18次。游戏水面特效实现方式太多。咱们这边介绍的是一最简单的UV动画(无顶点位移),整个mesh由4个顶点构成。实现了水面效果(左图),不动代码稍微修改下参数和贴图可以实现岩浆效果(右图)。有要思路是1,uv按时间去做正弦波移动2,在1的基础上加个凹凸图混合uv3,在1、2的基础上加个水流方向4,加上对雾效的支持,如没必要请自行删除雾效代码(把包含fog的几行代码删除)S..._unity 岩浆shader
文章浏览阅读5k次。广义线性模型是线性模型的扩展,它通过连接函数建立响应变量的数学期望值与线性组合的预测变量之间的关系。广义线性模型拟合的形式为:其中g(μY)是条件均值的函数(称为连接函数)。另外,你可放松Y为正态分布的假设,改为Y 服从指数分布族中的一种分布即可。设定好连接函数和概率分布后,便可以通过最大似然估计的多次迭代推导出各参数值。在大部分情况下,线性模型就可以通过一系列连续型或类别型预测变量来预测正态分布的响应变量的工作。但是,有时候我们要进行非正态因变量的分析,例如:(1)类别型.._广义线性回归模型
文章浏览阅读69次。环境保护、 保护地球、 校园环保、垃圾分类、绿色家园、等网站的设计与制作。 总结了一些学生网页制作的经验:一般的网页需要融入以下知识点:div+css布局、浮动、定位、高级css、表格、表单及验证、js轮播图、音频 视频 Flash的应用、ul li、下拉导航栏、鼠标划过效果等知识点,网页的风格主题也很全面:如爱好、风景、校园、美食、动漫、游戏、咖啡、音乐、家乡、电影、名人、商城以及个人主页等主题,学生、新手可参考下方页面的布局和设计和HTML源码(有用点赞△) 一套A+的网_垃圾分类网页设计目标怎么写
文章浏览阅读614次,点赞7次,收藏11次。之前找到一个修改 exe 中 DLL地址 的方法, 不太好使,虽然能正确启动, 但无法改变 exe 的工作目录,这就影响了.Net 中很多获取 exe 执行目录来拼接的地址 ( 相对路径 ),比如 wwwroot 和 代码中相对目录还有一些复制到目录的普通文件 等等,它们的地址都会指向原来 exe 的目录, 而不是自定义的 “lib” 目录,根本原因就是没有修改 exe 的工作目录这次来搞一个启动程序,把 .net 的所有东西都放在一个文件夹,在文件夹同级的目录制作一个 exe._.net dll 全局目录
文章浏览阅读1.5k次。本文为转载,原博客地址:http://blog.csdn.net/hujingshuang/article/details/46910259简介 BRIEF是2010年的一篇名为《BRIEF:Binary Robust Independent Elementary Features》的文章中提出,BRIEF是对已检测到的特征点进行描述,它是一种二进制编码的描述子,摈弃了利用区域灰度..._breif description calculation 特征点
文章浏览阅读4.1k次,点赞21次,收藏79次。本文是《基于SpringBoot的房屋租赁管理系统》的配套原创说明文档,可以给应届毕业生提供格式撰写参考,也可以给开发类似系统的朋友们提供功能业务设计思路。_基于spring boot的房屋租赁系统论文