从通知服务扩展进行日志记录



所以目前我正在这样做:

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,那么操作系统将终止扩展,我将没有时间完成我的日志。

在应用扩展执行其任务(或启动 后台会话来执行它(,系统终止 外延。

文档:附加应用的生命周期

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

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

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

你走在正确的轨道上。

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

对于日志的网络调用,将其URLSessionConfiguration stimeoutIntervalForRequest设置为小于 5 秒。这样,您就不会等待它完成。

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

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

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

最新更新