迅速丰富的通知.图片未显示在通知中 [英] Rich Notification in swift. Image not show in notification

查看:22
本文介绍了迅速丰富的通知.图片未显示在通知中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发出丰富的通知以在通知中显示图像,但每当我发送简单的消息时,我都会收到通知.前 2 天我试图在通知中显示图像,但没有完成.请帮我做这件事.

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.

提前致谢

这是我的代码.

在通知服务扩展中

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

    }

这是我的通知结构

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

推荐答案

使用以下代码

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

还有 info.plist 中的以下代码

also the following code in info.plist

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

在 Info.plist 的 NSExtension NSDictionary 中添加这个键

add this key in NSExtension NSDictionary in Info.plist

    <key>NSExtensionAttributes</key>
    <dict/>

这篇关于迅速丰富的通知.图片未显示在通知中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆