xcode 如何从远程通知启动liveActivity· Swift

kx1ctssn  于 11个月前  发布在  Swift
关注(0)|答案(2)|浏览(143)

当实现锁定屏幕实时活动小部件调试的目的,我有一个按钮,运行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)

    }

字符串
我尝试从appDelegate的didReceiveRemoteNotification运行startLiveActivity()函数:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse) async {
        
        LiveActivityHelper.shared.startLiveActivity()
}


从通知扩展中,我有:

class NotificationService: UNNotificationServiceExtension, UNUserNotificationCenterDelegate {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

    ...
    LiveActivityHelper.shared.startLiveActivity()


所有这些方法都会导致相同的结果,即只有在打开应用程序时才会出现小部件。
Apple's documentation包括从远程通知更新小部件,但不包括如何使用该方法启动它。

js4nwp54

js4nwp541#

Live Activity只能在应用处于前台时启动,因为其目的是根据文档跟踪用户启动的功能。
发送您的推送通知,让您的用户打开您的应用,然后启动Activity。您所需的流被明确声明为不受支持。

b4qexyjb

b4qexyjb2#

使用可操作的通知类型可以帮助您引导用户点击并按住它来添加:

func userNotificationCenter(_ center: UNUserNotificationCenter,
       didReceive response: UNNotificationResponse,
       withCompletionHandler completionHandler: 
         @escaping () -> Void) {
       
   // Get the details from the original notification.
   let userInfo = response.notification.request.content.userInfo
        
   // Perform the task associated with the action.
   switch response.actionIdentifier {
   case "liveActivity":
      initiateLiveActivity(with: userInfo)
      break

   // Handle other actions…
   default:
      break
   }
    
   // Always call the completion handler when done.    
   completionHandler()
}

字符串
对于远程推送通知,您需要为此准备有效的有效负载。有关Apple documentation的可操作通知的更多详细信息。

相关问题