1

I make rich notification to show image in notification but whenever i send simple message then i get notification. Last 2 day i am trying to show image in notification but it was not done. Please help me to do this.

Thank you in advance

This is my code.

In Notification Service Extension

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        // Get the custom data from the notification payload
        if let data = request.content.userInfo["data"] as? [String: String] {
            // Grab the attachment
            if let urlString = data["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()
            }
        }

    }

This is my notification structure

{
 "aps" : {
    "alert" : {
        "title" : "Push Remote Rich Notifications",
        "subtitle" : "iOS 10 - New API",
        "body" : "Media Image Rich notification"
        },
    "mutable-content" : 1,
    "category" : "imageIdentifier"
    },
    "data" : {
      "attachment-url": "https://raw.githubusercontent.com/Sweefties/iOS10-NewAPI-UserNotifications-Example/master/source/iOS10-NewAPI-UserNotifications-Example.jpg"
    }
}
Mohit
  • 126
  • 2
  • 10
  • From the doc: "Your extension has a limited amount of time (no more than 30 seconds) to modify the content and execute the contentHandler block. If you do not execute that block in a timely manner, the system calls your extension’s serviceExtensionTimeWillExpire method to give you one last chance to execute the block. If you do not, the system presents the notification’s original content to the user." Do you fall into that case? – Larme Sep 14 '17 at 09:55
  • I think No i am not manage that....but i recive notification instantly but image not show. – Mohit Sep 14 '17 at 10:26
  • have you find out your solution?I am stuck in same situation. – riddhi Sep 16 '17 at 09:05
  • try very small images which can be downloaded in seconds. the image you are using is very large in size. – Krishna Datt Shukla Sep 18 '17 at 11:20
  • Hello @KrishnaDattShukla. using 7 kb size of image but still not get image – Mohit Sep 18 '17 at 12:00
  • Hello @riddhi. srry but no still have problem .... And U? – Mohit Sep 18 '17 at 12:01
  • Is your extension method is being called ? – Krishna Datt Shukla Sep 18 '17 at 12:25
  • I solved my problem by allowing App Transport Security Settings in notification service info.plist. you can try it. – riddhi Sep 19 '17 at 06:53
  • hello @KrishnaDattShukla. put breakpoint in extension class but no such process in there so i think extension class is not called. – Mohit Sep 19 '17 at 07:04
  • hello @riddhi i am not put App Transfer security in notification info.plist i will try it... – Mohit Sep 19 '17 at 07:06
  • Hello @Mohit, are you running the extension scheme or your project scheme ? In order to get the extension call you will need to run the Extension scheme, not the app scheme. – Krishna Datt Shukla Sep 19 '17 at 07:09
  • @KrishnaDattShukla i am call extension schema. – Mohit Sep 19 '17 at 07:16
  • Have you configured the category name in your plist ? – Krishna Datt Shukla Sep 19 '17 at 07:34
  • @KrishnaDattShukla . Yes configure category name in project info.plist. – Mohit Sep 19 '17 at 11:37

1 Answers1

1

Use this following code

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)

     guard let bestAttemptContent = bestAttemptContent else {
         return
     }
     guard let attachmentUrlString = request.content.userInfo["pic_url"] as? String else {
         return
     }
     guard let url = URL(string: attachmentUrlString) else {
         return
     }

     URLSession.shared.downloadTask(with: url, completionHandler: { (optLocation: URL?, optResponse: URLResponse?, error: Error?) -> Void in
         if error != nil {
             print("Download file error: \(String(describing: error))")
             return
         }
         guard let location = optLocation else {
             return
         }
         guard let response = optResponse else {
             return
         }

         do {
             let lastPathComponent = response.url?.lastPathComponent ?? ""
             var attachmentID = UUID.init().uuidString + lastPathComponent

             if response.suggestedFilename != nil {
                 attachmentID = UUID.init().uuidString + response.suggestedFilename!
             }

             let tempDict = NSTemporaryDirectory()
             let tempFilePath = tempDict + attachmentID

             try FileManager.default.moveItem(atPath: location.path, toPath: tempFilePath)
             let attachment = try UNNotificationAttachment.init(identifier: attachmentID, url: URL.init(fileURLWithPath: tempFilePath))

             bestAttemptContent.attachments.append(attachment)
         }
         catch {
             print("Download file error: \(String(describing: error))")
         }

         OperationQueue.main.addOperation({() -> Void in
             self.contentHandler?(bestAttemptContent);
         })
     }).resume()
 }

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

also the following code in info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

add this key in NSExtension NSDictionary in Info.plist

    <key>NSExtensionAttributes</key>
    <dict/>
Ruchin Somal
  • 1,073
  • 12
  • 14