我正在尝试发送images推送通知,我已在应用程序委托中进行了通知注册,并且apns设备令牌正在正确生成。我也已经在服务分机中编写了如下代码:
images
import UserNotifications class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) // Get the custom data from the notification payload if let notificationData = request.content.userInfo["data"] as? [String: String] { // Grab the attachment if let urlString = notificationData["attachment-url"], let fileUrl = URL(string: urlString) { // Download the attachment URLSession.shared.downloadTask(with: fileUrl) { (location, response, error) in if let location = location { // Move temporary file to remove .tmp extension let tmpDirectory = NSTemporaryDirectory() let tmpFile = "file://".appending(tmpDirectory).appending(fileUrl.lastPathComponent) let tmpUrl = URL(string: tmpFile)! try! FileManager.default.moveItem(at: location, to: tmpUrl) // Add the attachment to the notification content if let attachment = try? UNNotificationAttachment(identifier: "", url: tmpUrl) { self.bestAttemptContent?.attachments = [attachment] } } // Serve the notification content self.contentHandler!(self.bestAttemptContent!) }.resume() } } } }
。并且json中的有效负载如下
{ "aps": {"sound":"default","alert": {"title":"iOS","body":"Hello Dude...."}, "mutable-content": 1}, "CustomData": {"mType":"alert","m":"Hello Dude...."}, "Attachement-url":"https://pusher.com/static_logos/320x320.png" }
我收到 标题 和 消息, 但是 图像 未显示。请指导如何在推送通知中获取图片
这行:
if let urlString = notificationData["attachment-url"], let fileUrl = URL(string: urlString) {
在userInfo字典中寻找attachment-url作为data对象子项的值。它正在寻找这个:
attachment-url
data
{ "aps" : { ... }, "data" : { "attachment-url" : "some url" } }
但是您的问题中的有效载荷是这样的:
{ "aps":{ "sound":"default", "alert": { "title":"iOS", "body":"Hello Dude...." }, "mutable-content": 1 }, "CustomData": { "mType":"alert", "m":"Hello Dude...." }, "Attachement-url":"https://pusher.com/static_logos/320x320.png" }
“数据”部分不存在,attachment-url键也不存在。
更改您的Swift代码以匹配有效载荷中的内容,您应该能够获取图像URL并下载它。
如果您收到没有通知你将有一个很大的问题 不是 对于安装URL键或附件网址是不是正确格式的URL。在这种情况下,您if let将不会被输入,并且contentHandler不会被调用!这不仅会导致服务扩展被锁定,还会阻止传递没有附件URL的任何通知!添加一个else,contentHandler以解决此问题。
if let
contentHandler
else
下载后,尽管存在另一个问题。iOS将需要知道您要在附件中放入哪种数据。附件选项字典允许您包括有关附件的类型信息。获取下载文件的MIME类型,然后从中创建一个统一类型标识符。然后,可以在选项字典中使用统一类型标识符字符串。
我将在iOS通知书中深入介绍所有这些内容。现在可用的示例章节涉及将图像添加到通知中。