0

所以目前我正在这样做:

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    logger = AnalyticsManager.shared
    self.contentHandler = contentHandler
    bestAttemptContent = (request.content.mutableCopy() as! UNMutableNotificationContent)
    if let notificationContent = bestAttemptContent {
        extensionHandler = ServiceExtensionHandler(notificationContent: notificationContent, logger: AnalyticsManager.shared)
        extensionHandler?.handleNotificationRequest { modifiedNotificationContent in
            guard let modifiedNotificationContent = modifiedNotificationContent else {
                contentHandler(notificationContent)
                return
            }
            contentHandler(modifiedNotificationContent)
        }
    } else {
        contentHandler(request.content)
        return
    }
}

如果图像下载成功,我ServiceExtensionHandler将返回修改后的通知。到目前为止,一切都很好。

但是一旦图像下载成功,我想记录一个事件。问题是如果我返回,contentHandler那么操作系统将终止扩展,我将没有时间完成我的日志。

在应用程序扩展执行其任务(或启动后台会话以执行它)后不久,系统会终止扩展。

文档:应用程序扩展的生命周期

目前它正在工作,但不能保证额外的网络调用正常工作。

如果日志返回,我只能返回该完成处理程序,但是日志可能会在 60 秒内超时,这本身也是另一个问题。

有没有人想到任何解决方案?

4

1 回答 1

0

你在正确的轨道上。

您应该contentHandler最终从派生自日志记录的网络回调的回调中返回。只需稍作改动:

对于您的日志网络调用,将其URLSessionConfiguration s设置timeoutIntervalForRequest为低于 5 秒的值。这样,您就不会等待很长时间才能完成。

这是伪代码,但对于执行日志记录的对象,请执行以下操作:

if let imageData = data {
    self?.log("downloadSuccess") {
        completionHandler(imageData, nil)
   }
}

它要么在不到 5 秒的时间内成功/失败,要么如果它将超时,则不会超过 5 秒。

于 2020-06-11T21:41:23.677 回答