UNNotificationAttachment with UIImage or Remote URL

后端 未结 4 1419
旧巷少年郎
旧巷少年郎 2020-12-05 15:02

In my Notification Service Extension I am downloading an image from a URL to show as UNNotificationAttachment in a notification.

So I have

4条回答
  •  旧巷少年郎
    2020-12-05 15:28

    I've created a blogpost on this subject, focused on GIF images. But it should be easy to rewrite my code for simply images.

    You need to create a Notification Service Extension:

    And include this code:

    final class NotificationService: UNNotificationServiceExtension {
    
        private var contentHandler: ((UNNotificationContent) -> Void)?
        private var bestAttemptContent: UNMutableNotificationContent?
    
        override internal func didReceiveNotificationRequest(request: UNNotificationRequest, withContentHandler contentHandler: (UNNotificationContent) -> Void){
            self.contentHandler = contentHandler
            bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
    
            func failEarly() {
                contentHandler(request.content)
            }
    
            guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
                return failEarly()
            }
    
            guard let attachmentURL = content.userInfo["attachment-url"] as? String else {
                return failEarly()
            }
    
            guard let imageData = NSData(contentsOfURL:NSURL(string: attachmentURL)!) else { return failEarly() }
            guard let attachment = UNNotificationAttachment.create("image.gif", data: imageData, options: nil) else { return failEarly() }
    
            content.attachments = [attachment]
            contentHandler(content.copy() as! UNNotificationContent)
        }
    
        override func serviceExtensionTimeWillExpire() {
            // Called just before the extension will be terminated by the system.
            // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
            if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
                contentHandler(bestAttemptContent)
            }
        }
    
    }
    
    extension UNNotificationAttachment {
    
        /// Save the image to disk
        static func create(imageFileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
            let fileManager = NSFileManager.defaultManager()
            let tmpSubFolderName = NSProcessInfo.processInfo().globallyUniqueString
            let tmpSubFolderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(tmpSubFolderName, isDirectory: true)
    
            do {
                try fileManager.createDirectoryAtURL(tmpSubFolderURL!, withIntermediateDirectories: true, attributes: nil)
                let fileURL = tmpSubFolderURL?.URLByAppendingPathComponent(imageFileIdentifier)
                try data.writeToURL(fileURL!, options: [])
                let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, URL: fileURL!, options: options)
                return imageAttachment
            } catch let error {
                print("error \(error)")
            }
    
            return nil
        }
    }
    

    For more information you can check my blogpost here: http://www.avanderlee.com/ios-10/rich-notifications-ios-10/

提交回复
热议问题