使用UIImage或远程URL进行UNNotificationAttachment

时间:2016-08-23 13:50:16

标签: ios swift uiimage unnotificationattachment

在我的Notification Service Extension我正在从网址下载图片,并在通知中显示为UNNotificationAttachment

所以我把这个图像作为UIImage,并且没有看到需要在光盘上的app目录/组容器中写入它来设置通知。

使用UIImage创建UNNotificationAttachment是否有好方法? (应该适用于本地和远程通知)

4 个答案:

答案 0 :(得分:24)

  1. 在tmp文件夹中创建目录
  2. NSData的{​​{1}}表示写入新创建的目录
  3. 使用url为tmp文件夹
  4. 中的文件创建UNNotificationAttachment
  5. 清理tmp文件夹
  6. 我在UIImage

    上写了一个扩展程序
    UINotificationAttachment

    所以要从extension UNNotificationAttachment { static func create(identifier: String, image: UIImage, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? { let fileManager = FileManager.default let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true) do { try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil) let imageFileIdentifier = identifier+".png" let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier) guard let imageData = UIImagePNGRepresentation(image) else { return nil } try imageData.write(to: fileURL) let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL, options: options) return imageAttachment } catch { print("error " + error.localizedDescription) } return nil } } 创建UNUserNotificationRequest UNUserNotificationAttachment,你就可以这样做......

    UIImage

    这应该有效,因为let identifier = ProcessInfo.processInfo.globallyUniqueString let content = UNMutableNotificationContent() content.title = "Hello" content.body = "World" if let attachment = UNNotificationAttachment.create(identifier: identifier, image: myImage, options: nil) { // where myImage is any UIImage that follows the content.attachments = [attachment] } let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 120.0, repeats: false) let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { (error) in // handle error } 会将图像文件复制到自己的位置。

答案 1 :(得分:6)

我已经创建了一个关于这个主题的博客文章,专注于GIF图像。但是为简单的图像重写我的代码应该很容易。

您需要创建通知服务扩展: Notification Service Extension

并包含以下代码:

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

有关详细信息,请点击此处查看我的博文: http://www.avanderlee.com/ios-10/rich-notifications-ios-10/

答案 2 :(得分:1)

这是一个完整的示例,说明如何从互联网实际下载图像并将其附加到本地通知中(这是原始问题的一部分)。

let content = UNMutableNotificationContent()
content.title = "This is a test"
content.body = "Just checking the walls"

if let url = URL(string: "https://example.com/images/example.png") {

    let pathExtension = url.pathExtension

    let task = URLSession.shared.downloadTask(with: url) { (result, response, error) in
        if let result = result {

            let identifier = ProcessInfo.processInfo.globallyUniqueString                
            let target = FileManager.default.temporaryDirectory.appendingPathComponent(identifier).appendingPathExtension(pathExtension)

            do {
                try FileManager.default.moveItem(at: result, to: target)

                let attachment = try UNNotificationAttachment(identifier: identifier, url: target, options: nil)
                content.attachments.append(attachment)

                let notification = UNNotificationRequest(identifier: Date().description, content: content, trigger: trigger)
                UNUserNotificationCenter.current().add(notification, withCompletionHandler: { (error) in
                    if let error = error {
                        print(error.localizedDescription)
                    }
                })
            }
            catch {
                print(error.localizedDescription)
            }
        }
    }
    task.resume()
}

通常,如果下载的文件已经是有效图像,则无需重新创建图像。只需使用唯一名称和扩展名.png.jpg将下载的文件复制到当前的Temp目录即可。在现有的Temp目录中也不必创建子目录。

答案 3 :(得分:0)

UIImage中似乎不可能,我发现的所有解决方案都是下载图像并将其存储在本地。这也是有道理的,因为您将必须导入UIKit并不确定它是否与扩展兼容(以及在有更简单的解决方案时为什么要导入整个框架)。

Here是一种更简单且可测试的解决方案,不需要使用FileManager。