2016-11-22 126 views
1

我試圖在ios 10中實現豐富的遠程通知。我實現了這個代碼。收到通知後的控件會在這裏,但我不知道如何下載圖像並顯示在通知中。提前致謝。對於豐富的遠程通知使用UNNotificationServiceExtension

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) 

    if let bestAttemptContent = bestAttemptContent { 
     // Modify the notification content here... 
     //print("title for image = \(bestAttemptContent.title)") 
     bestAttemptContent.title = "\(bestAttemptContent.title) [modified]" 

     contentHandler(bestAttemptContent) 
    } 

} 



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

} 

回答

0

你會得到你的notificationData這樣

"attachment-url": "https://yourimage.png" 

的附件,這是你如何使用它

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

here

+0

感謝您的回覆@Rajat。我試過這個,但它仍然沒有下載圖像。仍然只顯示文本數據。我不知道我在做什麼錯 – Prajyot

+0

檢查文件是否正在下載,也檢查你是否從通知數據中獲得有效的URL – Rajat

+0

是的,網址是有效的。但是他們要在什麼地方儲存?我看過照片,沒有。 – Prajyot

0

最後其工作參考。這裏的問題是,我不得不添加

NSAppTransportSecurity

標籤在擴展的plist中。添加此標籤後,它開始顯示圖像。希望它能幫助別人。