ios - UNNotificationServiceExtension 偶尔更新通知失败

标签 ios iphone swift ios10 serviceextension

我有一个用 Swift 编写的 UNNotificationServiceExtension。它所做的一切:

  • 设置通知标题
  • 设置通知正文
  • 加载图片并调用contentHandler()

这是我在做什么的简短版本:

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!)
    }
}

95% 的情况下 - 它工作得很好。然而,偶尔通知到达时没有任何变化(即标题、正文保持不变,没有附加图像)。

我知道:

  • 不是超时:serviceExtensionTimeWillExpire 没有被调用
  • 它看起来不像 UNNotificationServiceExtension 崩溃:我添加了大量的 NSLog() 调用来检查设备日志 - self.contentHandler !(self.bestAttemptContent!) 触发
  • 这种情况在我的 iPhone 上比在 iPad 上更常见
  • 我没有在设备日志中找到任何关于此问题的线索

有人遇到过这个问题吗?任何解决方法?想法?

最佳答案

当该功能首次公布时,我构建了一个 UNNotificationServiceExtension。两个想法:

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

  2. 服务扩展是它自己独立的二进制文件和进程。系统可能没有启动该进程,或者无法打开您的应用程序进程和服务扩展之间的链接。我还会检查 sysdaignose 是否有任何表明进程的 mach 端口为 nil 的内容。

关于ios - UNNotificationServiceExtension 偶尔更新通知失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40162926/

相关文章:

Swift 包管理器 - UIKit 依赖

ios - 编辑 NSUserDefaults 托管配置字典

ios - 每次打开 iOS 应用程序时都被迫创建新的 Quickblox session

iphone - Push Notification 推送出现两次?

iphone - 如何从命令行运行 UIAutomation 脚本到模拟器

ios - 访问 NSError.localizedDescription 时偶尔崩溃

ios - swift 3 : compress ImageView Vertically depending on its image height

objective-c - 如何获取数组中 ipodLibrary 中所有歌曲的列表

iphone - 检测没有磁盘空间iPhone SDK

Swift:如何使这个函数通用