2016-08-23 66 views
9

在我的Notification Service Extension中,我正在從URL中下載圖像以在通知中顯示爲UNNotificationAttachment使用UIImage或遠程URL進行UNNotificationAttachment

所以我把這個圖像作爲UIImage,並沒有看到需要將它寫在我的應用程序目錄/組光盤容器中,只是爲了設置通知。

有沒有一種很好的方法創建一個帶有UIImage的UNNotificationAttachment (應該是appliable本地和遠程通知)

回答

14
  1. 在TMP文件夾中創建目錄
  2. UIImageNSData表示到新創建的目錄
  3. 與URL到文件中創建UNNotificationAttachment TMP文件夾
  4. 清理TMP文件夾

我就寫了延長

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

所以從UIImage創建UNUserNotificationRequestUNUserNotificationAttachment你可以簡單地折騰這樣

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 
} 

這應該工作,因爲UNNotificationAttachment將圖像文件複製到自己的位置。

+4

我沒有看到「第4步清理tmp文件夾」 – kauai

+0

如何進入第4步,刪除臨時文件夾?通知被打開後? – pasevin

+0

臨時文件夾被系統自動清理其未清理的緩存目錄 – Luke

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/

+0

儘管這個鏈接可能回答這個問題,但最好在這裏包含答案的重要部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。有關更多詳情,請參閱[答案]。 –

+1

@VinceBowdren你是完全正確的。改變了我的答案! – Antoine

+1

以及何時從臨時目錄中刪除圖像? – pasevin