2017-04-22 30 views
2

我想附加圖像到我的本地通知給出圖像的URL。這是創建附件的擴展:將圖像附加到通知圖像的URL

import UserNotifications 

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

當我安排一個新的通知,我用這樣的:

// url of the image such as http://www.unsplash.com/image.png 
let data = try? Data(contentsOf: url) 
guard let myImage = UIImage(data: data!) else { return } 

if let attachment = UNNotificationAttachment.create(identifier: key, image: myImage, options: nil) { 
    content.attachments = [attachment] 
} 

enter image description here

創建通知這樣凍結的應用幾秒鐘,因爲該應用程序同步下載圖像。我也嘗試使用DispatchQueue,但它沒有改變任何東西。我做錯了什麼?

回答

2

您的代碼下載圖像,解析它以創建UIImage,將圖像轉換回一個PNG數據塊,然後將此數據寫入臨時文件。

您可以跳過創建UIImage的步驟並將其轉換回文件。

嘗試使用URLSessionURLDataTask

let fileURL = ... 
let task = URLSession.shared.dataTask(with: url) { (data, _, _) in 
    do { 
     try imageData.write(to: fileURL) 
     let attachment = UNNotificationAttachment.create(identifier: key, image: myImage, options: nil) 
     // call closure to call back with attachment and/or error 
    } 
    catch let ex { 
     // call closure with error 
    } 
} 
task.resume() 

我省略了一些錯誤處理等細節,但是這應該給你什麼需要以異步方式做到這一點的總體思路。 URLSession使用GCD來執行異步網絡。

0

使用Alamofire異步下載圖像,然後嘗試顯示它。

let destination: DownloadRequest.DownloadFileDestination = { 
    _, _ in 
    var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] 
    documentsURL.appendPathComponent("image.jpg") 
    return (documentsURL, [.removePreviousFile, .createIntermediateDirectories]) 
} 
Alamofire.download(url, to: destination).response { 
    response in 
    // do whatever you want with your image, for example if it is an audio file: 
    do { 
     self.player = try AVAudioPlayer(contentsOf: URL(string: "\(response.destinationURL!)")!) 
     self.player.volume = 1.0 
     self.player.play() 
    } catch { 
     print(error) 
    }   
}