问题描述
我正在努力在 iOS 10 中向我的推送通知添加图像.
I'm struggling with adding an image to my Push Notification in iOS 10.
我添加了一个通知服务扩展,并使用了以下代码:
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 推送通知中的媒体附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!