我正在尝试在推送通知中发送images
我已在app delegate中进行通知注册,并且apns设备令牌正在生成。
另外,我在服务分机中编码如下:
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"
}
我收到标题和消息,但图片未来。 请指导如何在推送通知中获取图像
答案 0 :(得分:2)
对于Swift,如果您需要,可以尝试使用this framework
同时在你的手势中添加“content-available”:1
或者您可以尝试这样下载,
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as?UNMutableNotificationContent)
bestAttemptContent?.title = request.content.title
bestAttemptContent?.body = request.content.body
guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
return failEarly()
}
guard let payload = content.userInfo["CustomData"] as? [String: Any] else {
return failEarly()
}
guard let attachmentURL = payload["Attachement-url"] as? String else {
return failEarly()
}
let identifierName = getIdentifierName(fileURL: attachmentURL)
let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
guard let imageData = NSData(contentsOf:NSURL(string: attachmentURL)! as URL) else { return failEarly() }
guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: identifierName, data: imageData, options: nil, tmpSubFolderName: tmpSubFolderName) else { return failEarly() }
content.attachments = [attachment]
contentHandler(content.copy() as! UNNotificationContent)
}
}
func getIdentifierName(fileURL : String) -> String {
var identifierName : String = "image.jpg"
if !fileURL.isEmpty() {
identifierName = "file.\((fileURL as NSString).lastPathComponent)"
}
return identifierName
}
func failEarly() {
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
extension UNNotificationAttachment {
static func create(imageFileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?, tmpSubFolderName : String) -> UNNotificationAttachment? {
let fileManager = FileManager.default
let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
let fileURLPath = NSURL(fileURLWithPath: NSTemporaryDirectory())
let tmpSubFolderURL = fileURLPath.appendingPathComponent(tmpSubFolderName, isDirectory: true)
do {
try fileManager.createDirectory(at: tmpSubFolderURL!, withIntermediateDirectories: true, attributes: nil)
let fileURL = tmpSubFolderURL?.appendingPathComponent(imageFileIdentifier)
try data.write(to: fileURL!, options: [])
let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL!, options: options)
return imageAttachment
} catch let error {
print("error \(error)")
}
return nil
}
}
答案 1 :(得分:0)
此行:
if let urlString = notificationData["attachment-url"], let fileUrl = URL(string: urlString) {
正在寻找一个attachment-url
值作为userInfo字典中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
的{{1}}来解决此问题。
下载完成后,就会出现另一个问题。 iOS将需要知道您要在附件中放入哪种数据。附件选项字典使您可以包括有关附件的类型信息。获取下载文件的MIME类型,然后从中创建一个统一类型标识符。然后可以在选项字典中使用统一类型标识符字符串。
我在iOS Notifications book中详细介绍了所有这些内容。现在可用的示例章节介绍了将图像添加到通知中。