【问题标题】:Images in iOS push notificationiOS 推送通知中的图像
【发布时间】:2018-06-14 08:55:42
【问题描述】:

我正在尝试在推送通知中发送images 我已经在应用程序委托中进行了通知注册,并且 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中的payload如下

{
    "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"
} 

我收到了 titlemessage,但 image 没有收到。 请指导如何在推送通知中获取图像

【问题讨论】:

  • 请将您的有效载荷密钥与代码匹配。检查代码中的Attachement-url
  • 你能用swift代码指导我吗?在推送通知中包含图像需要完成的所有过程

标签: ios swift imageview apple-push-notifications


【解决方案1】:

对于 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
        }
    }

【讨论】:

【解决方案2】:

这一行:

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 不是格式正确的 URL,您将遇到大问题。在这些情况下,您的if let 将不会被输入,contentHandler 也不会被调用!这不仅会导致服务扩展锁定,而且会阻止任何没有附件 URL 的通知被传递!添加一个调用contentHandlerelse 来解决此问题。

一旦你下载了它,虽然还有另一个问题。 iOS 需要知道您在附件中放入了什么样的数据。附件选项字典允许您包含有关附件的类型信息。获取下载文件的 MIME 类型并从中创建统一类型标识符。然后可以在选项字典中使用统一类型标识符字符串。

我在iOS Notifications book 中深入介绍了所有这些内容。现在可用的示例章节处理向通知添加图像。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-26
    • 2020-03-15
    • 2016-10-16
    • 1970-01-01
    • 2012-12-18
    • 2017-04-19
    • 2011-08-07
    • 1970-01-01
    相关资源
    最近更新 更多