iOS16.1 实时活动 (Live Activity)&灵动岛适配-程序员宅基地

技术标签: swiftui  iOS  ios  

前言

苹果在 WWDC22 中,提出了实时活动(Live Activity)的概念,以便于用户在锁屏查看一些应用实时活动的更新。并且ActivityKit实现了灵动岛视图的自定义。经过我近两个月的学习,总结出了一些经验分享出来供大家批评和指正。

说明

iOS16.1 锁屏界面上新增了实时活动界面,目前仅有iPhone 14 ProiPhone 14 Pro Max 两款机型上拥有灵动岛。实时活动包括了锁屏界面和灵动岛界面两个部分的内容,示例如下图所示:
示例
灵动岛部分示例
相较于iOS16.0的锁屏小组件,实时活动是显示在通知区域,且拥有更自由的视图定制和刷新方式。和小组件一样,它也限制了视图上的动画效果显示。我们可以使用实时更新来做一些有意思的设计和功能。例如上面演示的 运动监测、订单进度、赛事成绩等。

场景限制及建议(节选自参考文献1)

  1. 最多持续8小时,使用场景需要考虑,8小时之后无法再刷新(目前实际还可以,但是以官方文档为准,自行限制),12小时后强制消失(因此跨天场景不考虑)
  2. 创建时,需要app在前台主动创建,没启动应用的时候不能自己出现(与特定业务绑定,比如下单后显示)
  3. 卡片本身禁止定位以及网络请求,少量(4KB)数据可通过通知发送,或通过后台活动刷新数据
  4. 同场景多卡片由于样式趋同且折叠,不建议同时创建多卡片

灵动岛适配必要性(节选自参考文献1)

  1. 与锁屏Live Activity共享数据,在支持灵动岛的机型下,用户在非锁屏页面时,信息的更新会以灵动岛的形式展示更新
  2. Live Activity创建后,灵动岛就可以进行点击响应了,如果不适配的话,点击灵动岛会自动进入主程序,并且长按会变成一个没有任何信息的黑块
  3. iPhone14 Pro、iPhone14 Pro Max用户占比逐渐升高

开发基础知识(节选自参考文献2)

  1. 设备只支持iPhone,并且是有“药丸屏”的iPhone14Pro和14Pro Max上;
  2. Max系统版本、编译器及iOS系统版本:>=MacOS12.4、>=Xcode14.0+beta4、>=iOS16.1+beta
  3. 使用 ActivityKit 用于配置、开始、更新、结束实现 Live Activity 能力。使用 WidgetKit 、SwiftUIwidget小组件中创建 Live Activity的用户界面,这样小组件和 Live Activity的代码是可以共享;
  4. Live Activity目前只能通过 ActivityKit 从主工程获取数据,或者从 远程通知 获取最新数据;无法访问网络或者接受位置更新信息
  5. ActivityKit 和 远程通知推送 更新的数据不能超过4KB
  6. Live Activity可以给不同的控制绑定不同的 deeplink,使其跳转到不同的页面;
  7. Live Activity在用户主动结束前最多存活8小时;
  8. 已经结束的 Live Activity 在锁屏也最多保留4小时,所以一个Live Activity 最长可以停留12小时;
  9. 最多同时存在两组 Live Activity ,排列顺序待发现
  10. Live Activity只有Swift版本,项目是 OC的话需要桥接。

实现

一、主程序配置

需要在主程序的Info.plist中添加键值:Supports Live ActivitiesYES

二、扩展部分

1.创建WidgetExtension

如果项目中已经有WidgetExtension,可以直接快进到第二步。
创建WidgetExtension

2.认识代码

1
在这里插入图片描述

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

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(可变部分)不可变部分组成。更新所需要传递的就是可变部分的内容。

三、主程序部分

实时活动的开启、更新和结束都需要在主程序进行管理。

1.开启

// 使用方法
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)" )
}

2.更新

// 使用方法
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)
}

3.结束

// 使用方法
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)
}

4.状态获取

创建成功后可以使用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.
            }
        }
    }
}

5.PushToken获取

如果需要使用通知进行更新,需要将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)
            }
        }
    }
}

6.权限

实时活动
实时活动的权限无法监听获得,只能主动进行判断,需要在进行创建前进行判断来提示用户

// 实时活动是否可用,包括权限是否开启和手机是否支持实时活动
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&A

实时活动的网络研讨会上自由提问时间里一些开发者的问题和回答

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 11iOS版本全部为 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() 方法,如果删除minimalcompactLeading中的getLoveryAvatatImage(),不能正常显示的两个手机就可以正常显示了。所以,建议设计师将这两处换成了显示AppLogo图片了。

// 实时活动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())
            }
        }
    }
}

但是这个问题的根本原因却不知道,因为有的手机是可以正常使用的,只有那两台测试机无法正常使用。如果有人知道为什么请私信我,大家一起讨论,谢谢!!!

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_38718912/article/details/128150549

智能推荐

oracle 12c 集群安装后的检查_12c查看crs状态-程序员宅基地

文章浏览阅读1.6k次。安装配置gi、安装数据库软件、dbca建库见下:http://blog.csdn.net/kadwf123/article/details/784299611、检查集群节点及状态:[root@rac2 ~]# olsnodes -srac1 Activerac2 Activerac3 Activerac4 Active[root@rac2 ~]_12c查看crs状态

解决jupyter notebook无法找到虚拟环境的问题_jupyter没有pytorch环境-程序员宅基地

文章浏览阅读1.3w次,点赞45次,收藏99次。我个人用的是anaconda3的一个python集成环境,自带jupyter notebook,但在我打开jupyter notebook界面后,却找不到对应的虚拟环境,原来是jupyter notebook只是通用于下载anaconda时自带的环境,其他环境要想使用必须手动下载一些库:1.首先进入到自己创建的虚拟环境(pytorch是虚拟环境的名字)activate pytorch2.在该环境下下载这个库conda install ipykernelconda install nb__jupyter没有pytorch环境

国内安装scoop的保姆教程_scoop-cn-程序员宅基地

文章浏览阅读5.2k次,点赞19次,收藏28次。选择scoop纯属意外,也是无奈,因为电脑用户被锁了管理员权限,所有exe安装程序都无法安装,只可以用绿色软件,最后被我发现scoop,省去了到处下载XXX绿色版的烦恼,当然scoop里需要管理员权限的软件也跟我无缘了(譬如everything)。推荐添加dorado这个bucket镜像,里面很多中文软件,但是部分国外的软件下载地址在github,可能无法下载。以上两个是官方bucket的国内镜像,所有软件建议优先从这里下载。上面可以看到很多bucket以及软件数。如果官网登陆不了可以试一下以下方式。_scoop-cn

Element ui colorpicker在Vue中的使用_vue el-color-picker-程序员宅基地

文章浏览阅读4.5k次,点赞2次,收藏3次。首先要有一个color-picker组件 <el-color-picker v-model="headcolor"></el-color-picker>在data里面data() { return {headcolor: ’ #278add ’ //这里可以选择一个默认的颜色} }然后在你想要改变颜色的地方用v-bind绑定就好了,例如:这里的:sty..._vue el-color-picker

迅为iTOP-4412精英版之烧写内核移植后的镜像_exynos 4412 刷机-程序员宅基地

文章浏览阅读640次。基于芯片日益增长的问题,所以内核开发者们引入了新的方法,就是在内核中只保留函数,而数据则不包含,由用户(应用程序员)自己把数据按照规定的格式编写,并放在约定的地方,为了不占用过多的内存,还要求数据以根精简的方式编写。boot启动时,传参给内核,告诉内核设备树文件和kernel的位置,内核启动时根据地址去找到设备树文件,再利用专用的编译器去反编译dtb文件,将dtb还原成数据结构,以供驱动的函数去调用。firmware是三星的一个固件的设备信息,因为找不到固件,所以内核启动不成功。_exynos 4412 刷机

Linux系统配置jdk_linux配置jdk-程序员宅基地

文章浏览阅读2w次,点赞24次,收藏42次。Linux系统配置jdkLinux学习教程,Linux入门教程(超详细)_linux配置jdk

随便推点

matlab(4):特殊符号的输入_matlab微米怎么输入-程序员宅基地

文章浏览阅读3.3k次,点赞5次,收藏19次。xlabel('\delta');ylabel('AUC');具体符号的对照表参照下图:_matlab微米怎么输入

C语言程序设计-文件(打开与关闭、顺序、二进制读写)-程序员宅基地

文章浏览阅读119次。顺序读写指的是按照文件中数据的顺序进行读取或写入。对于文本文件,可以使用fgets、fputs、fscanf、fprintf等函数进行顺序读写。在C语言中,对文件的操作通常涉及文件的打开、读写以及关闭。文件的打开使用fopen函数,而关闭则使用fclose函数。在C语言中,可以使用fread和fwrite函数进行二进制读写。‍ Biaoge 于2024-03-09 23:51发布 阅读量:7 ️文章类型:【 C语言程序设计 】在C语言中,用于打开文件的函数是____,用于关闭文件的函数是____。

Touchdesigner自学笔记之三_touchdesigner怎么让一个模型跟着鼠标移动-程序员宅基地

文章浏览阅读3.4k次,点赞2次,收藏13次。跟随鼠标移动的粒子以grid(SOP)为partical(SOP)的资源模板,调整后连接【Geo组合+point spirit(MAT)】,在连接【feedback组合】适当调整。影响粒子动态的节点【metaball(SOP)+force(SOP)】添加mouse in(CHOP)鼠标位置到metaball的坐标,实现鼠标影响。..._touchdesigner怎么让一个模型跟着鼠标移动

【附源码】基于java的校园停车场管理系统的设计与实现61m0e9计算机毕设SSM_基于java技术的停车场管理系统实现与设计-程序员宅基地

文章浏览阅读178次。项目运行环境配置:Jdk1.8 + Tomcat7.0 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。项目技术:Springboot + mybatis + Maven +mysql5.7或8.0+html+css+js等等组成,B/S模式 + Maven管理等等。环境需要1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。_基于java技术的停车场管理系统实现与设计

Android系统播放器MediaPlayer源码分析_android多媒体播放源码分析 时序图-程序员宅基地

文章浏览阅读3.5k次。前言对于MediaPlayer播放器的源码分析内容相对来说比较多,会从Java-&amp;amp;gt;Jni-&amp;amp;gt;C/C++慢慢分析,后面会慢慢更新。另外,博客只作为自己学习记录的一种方式,对于其他的不过多的评论。MediaPlayerDemopublic class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal..._android多媒体播放源码分析 时序图

java 数据结构与算法 ——快速排序法-程序员宅基地

文章浏览阅读2.4k次,点赞41次,收藏13次。java 数据结构与算法 ——快速排序法_快速排序法