我有一个用 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
。两个想法:
由于系统问题,底层
URLSession
数据任务无法获取远程媒体。获取系统诊断并查找 libnetwork.dylib 中的错误。服务扩展是它自己独立的二进制文件和进程。系统可能没有启动该进程,或者无法打开您的应用程序进程和服务扩展之间的链接。我还会检查 sysdaignose 是否有任何表明进程的 mach 端口为
nil
的内容。
关于ios - UNNotificationServiceExtension 偶尔更新通知失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40162926/