iOS 10推送通知中的媒体附件 [英] Media Attachment in iOS 10 Push Notifications
问题描述
我正在努力将图像添加到iOS 10中的推送通知"中.
I'm struggling with adding an image to my Push Notification in iOS 10.
我添加了Notification Service Extension,并使用了以下代码:
I have added a Notification Service Extension, and have used the following code:
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let urlString = request.content.userInfo["image-url"] as? String, let fileUrl = URL(string: urlString) {
URLSession.shared.downloadTask(with: fileUrl) { (location, response, error) in
if let location = location {
let options = [UNNotificationAttachmentOptionsTypeHintKey: kUTTypePNG]
if let attachment = try? UNNotificationAttachment(identifier: "", url: location, options: options) {
self.bestAttemptContent?.attachments = [attachment]
}
}
self.contentHandler!(self.bestAttemptContent!)
}.resume()
}
}
我从下面的第一个答案中得到了这段代码.
I got this code from the first answer below.
我现在遇到的问题是,收到通知的时间很短,这表明必须进行下载,但没有显示附件.
The issue I'm having now is that the notification is received, with a short delay which indicates the download must be happening, but there is no attachment shown.
我假设正在调用serviceExtensionTimeWillExpire()
并仅显示bestAttempt
I am assuming that serviceExtensionTimeWillExpire()
is being called and just showing the bestAttempt
非常感谢您的帮助.
我相信我的APNs有效负载配置正确,
I have my APNs payload configured correctly, I believe:
apns: {
aps: {
alert: {
title: "Title",
subtitle: "Subtitle",
body: "Body"
},
"mutable-content": 1
},
"image-url": "https://helloworld.com/image.png"
}
推荐答案
您必须从通知的用户信息中拉出url,然后下载图像并为附件提供文件url.尝试类似的东西:
You have to pull the url out of the notification's user info, then download the image and give a file url to the attachment. Try something like:
if let urlString = request.content.userInfo["image-url"] as? String, let fileUrl = URL(string: urlString) {
URLSession.shared.downloadTask(with: fileUrl) { (location, response, error) in
if let location = location {
let options = [UNNotificationAttachmentOptionsTypeHintKey: kUTTypePNG]
if let attachment = try? UNNotificationAttachment(identifier: "", url: location, options: options) {
self.bestAttemptContent.attachments = [attachment]
}
}
self.contentHandler(self.bestAttemptContent)
}.resume()
}
这篇关于iOS 10推送通知中的媒体附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!