UNNotificationServiceExtension fails to update notifications occasionally

时间:2016-10-20 19:27:04

标签: ios iphone swift ios10 serviceextension

I have a UNNotificationServiceExtension written in Swift. All it does:

  • Set notification title
  • Set notification body
  • Load image & call contentHandler ()

Here's a shorted version of what am I doing:

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    self.contentHandler = contentHandler
    self.bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent

    bestAttemptContent!.title = GetNotificationTitle(userInfo)
    bestAttemptContent!.body = GetNotificationBody(userInfo)

    if let imageUrl = <get image url> {
        let imageLoaderTask = URLSession.shared.dataTask(with: URL.init(string: imageUrl)!) { (newsImageData, newsImageUrl, newsImageError) -> Void in
            if newsImageError == nil && newsImageData != nil {
                let documentDirectory = self.GetDocumentDirectory()
                if documentDirectory != nil {
                    let newsFileURL = documentDirectory?.appendingPathComponent("news_image").appendingPathExtension("png")
                    do {
                        try newsImageData?.write(to: newsFileURL!)
                        let attachment = try UNNotificationAttachment(identifier: "newsImage",
                                                                      url: newsFileURL!,
                                                                      options: nil)
                        self.bestAttemptContent?.attachments = [ attachment, ]
                        self.contentHandler!(self.bestAttemptContent!)
                        return
                    } catch {}
                }
            }
            self.contentHandler!(self.bestAttemptContent!)
        }
        imageLoaderTask.resume()
    } else {
        self.contentHandler!(self.bestAttemptContent!)
    }
}

In 95% cases - it works just fine. However, occasionally notification arrives without any changes (i.e. title, body remained the same, no image has been attached).

I know that:

  • It's not timeout: serviceExtensionTimeWillExpire is not called
  • It doesn't look like UNNotificationServiceExtension crashes: I've added plenty of NSLog() calls to check Device Logs - self.contentHandler!(self.bestAttemptContent!) fires
  • It happens more often on my iPhone rather than on iPad
  • I haven't found any single clue in Device Logs regarding the issue

Does anyone faced this issue? Any workarounds? Thoughts?

1 个答案:

答案 0 :(得分:0)

该功能首次发布时,我建立了UNNotificationServiceExtension。两个想法:

  1. 由于系统问题,基础URLSession数据任务无法获取远程媒体。进行系统诊断,并在libnetwork.dylib中查找错误。

  2. 服务扩展是其自己单独的二进制文件和进程。系统可能没有启动该过程,或者无法打开您的应用程序过程与服务扩展之间的链接。我还要检查sysdaignose是否显示该进程的马赫端口为nil