ios - iOS 推送通知中的图像

标签 ios swift imageview apple-push-notifications

我正在尝试在推送通知中发送图片 我已经在应用程序委托(delegate)中进行了通知注册,并且 apns 设备 token 正在正确生成。 另外,我在服务分机中编码如下:

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

我收到了标题消息,但没有收到图片。 请指导如何在推送通知中获取图像

最佳答案

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

关于ios - iOS 推送通知中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50853503/

相关文章:

ios - 在 Swift 中获取 RandomPlusMinus

database - CoreData 迁移新属性 Swift

java - 在 DialogFragment 从网站下载图片后,ImageView 上方出现青色条

ios - xcode 9 手动签名 ** 导出失败 **

ios - UIWebView:停止滚动,但不要禁用它

iphone - UITableView 无法一直滚动到底部

ios - iOS 上的 Realm : crash while creating nested object with primaryKey

swift - 如何为每个象限创建一个末端为圆角的圆

android - 加载图像时滑动圆角

android - 如何用半透明 View 覆盖 ImageView?