Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

swift - Images in iOS push notification

I am trying to send images in push notifications I have made the notifications registrations in app delegate and apns device token is generating properly. ALso I have coded in service ext as follows:

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()
    }
}
}
}

. And the payload in json is as follows

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

I am receiving the title and message but image is not coming. Please guide how to get image in push notifications

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For Swift, If you want you can try with this framework

Also Add "content-available":1 in your aps

OR you can try downloading like this,

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...