当出于调试目的实现锁屏实时活动小部件时,我有一个运行startLiveActivity()功能的按钮,应用程序正常运行小部件看起来完全正常工作。
但是,每当应用程序被杀死或在后台时收到远程推送通知时,我都需要显示此活动小部件,但它仅在应用程序位于前台时才出现,这对这里的情况没有真正的帮助。
class LiveActivityHelper: ObservableObject {
static var shared = LiveActivityHelper()
@Published var activity: Activity<Attributes>? = nil
func startLiveActivity() {
let state = Attributes.ContentState()
activity = try? Activity<Attributes>.request(attributes: Attributes(), contentState: state, pushType: nil)
}
Run Code Online (Sandbox Code Playgroud)
我尝试startLiveActivity()从 appDelegate 的 didReceiveRemoteNotification 运行该函数:
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse) async {
LiveActivityHelper.shared.startLiveActivity()
}
Run Code Online (Sandbox Code Playgroud)
从通知扩展中我有:
class NotificationService: UNNotificationServiceExtension, UNUserNotificationCenterDelegate {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { …Run Code Online (Sandbox Code Playgroud)