首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在UNNotificationServiceExtension中显示图像?

如何在UNNotificationServiceExtension中显示图像?
EN

Stack Overflow用户
提问于 2017-05-16 11:12:24
回答 2查看 3K关注 0票数 1

我将UNNotificationServiceExtension添加到应用程序中,成功地获得了数据,并加载了数据中的图像以推送通知,但无法在push通知窗口中显示该图像。请告诉我怎么修理?

代码语言:javascript
复制
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...
            bestAttemptContent.title = "Apple [modified]"
            bestAttemptContent.body = "Xcode"
            contentHandler(bestAttemptContent)

            let attachmentStorage = AttachmentStorage()

            if let imagePath = request.content.userInfo["image"] as? String {
                guard let url = URL(string: imagePath) else {
                    contentHandler(bestAttemptContent)
                    return
                }
                debugPrint("url", url)
                attachmentStorage.store(url: url) { (localURL, error) in
                    if let localURL = localURL {
                        debugPrint("path", localURL)
                        do {
                            let attachment = try UNNotificationAttachment.init(identifier: "image", url: localURL, options: nil)
                            bestAttemptContent.attachments = [attachment]
                            debugPrint("bestAttemptContent.attachments", bestAttemptContent.attachments, bestAttemptContent.attachments.count)
                            contentHandler(bestAttemptContent)
                            return
                        } catch {
                            contentHandler(bestAttemptContent)
                            return
                        }
                    }
                }
            }


            contentHandler(bestAttemptContent)
        }
    }

class AttachmentStorage {

    func store(url: URL, completion: ((URL?, Error?) -> ())?) {
        // obtain path to temporary file
        let filename = ProcessInfo.processInfo.globallyUniqueString
        let path = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(filename).jpeg")

        // fetch attachment
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            do {
                let _ = try data?.write(to: path)
                completion?(path, error)
            } catch {
                debugPrint(error.localizedDescription)
                completion?(nil, error)
            }
        }
        task.resume()
    }

}

日志

代码语言:javascript
复制
"bestAttemptContent.attachments" [<UNNotificationAttachment: 0x14dd626c0; identifier: image, family: Image, URL: file:///private/var/mobile/Containers/Data/PluginKitPlugin/1F13F774-B6CA-4567-9EF0-EA61C9A1F2A0/tmp/23A8E7EC-29FB-4C36-893D-5B0DCFB711B2-13808-000002A699FBF67B.jpeg, type: public.jpeg, options: <UNImageNotificationAttachmentOptions: 0x14dd5afd0>>] 1

我加了这个代码。即使您删除了contentHandler,有时您也会得到副本或没有图像。

代码语言:javascript
复制
let request = UNNotificationRequest.init(identifier: "image", content: bestAttemptContent, trigger: nil)
UNUserNotificationCenter.current().add(request) { (error) in
                                // handle error
                            }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-17 13:05:09

我做了这个,它对我有用

代码语言:javascript
复制
  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...
            if let imagePath = request.content.userInfo["image"] as? String {
                guard let url = URL(string: imagePath) else {
                    contentHandler(bestAttemptContent)
                    return
                }
                guard let imageData = NSData(contentsOf: url) else {
                    contentHandler(bestAttemptContent)
                    return
                }
                guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: "image.jpg", data: imageData, options: nil) else {
                    print("error in UNNotificationAttachment.create()")
                    contentHandler(bestAttemptContent)
                    return
                }
                bestAttemptContent.attachments = [ attachment ]
            }
            contentHandler(bestAttemptContent)
        }
    }


extension UNNotificationAttachment {

    /// Save the image to disk
    static func create(imageFileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
        let fileManager = FileManager.default
        let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
        guard let tmpSubFolderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true) else { return nil }

        do {
            try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil)
            let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier)
            try data.write(to: fileURL, options: [])
            let imageAttachment = try UNNotificationAttachment(identifier: imageFileIdentifier, url: fileURL, options: options)
            return imageAttachment
        } catch let error {
            print("error \(error)")
        }

        return nil
    }

}
票数 2
EN

Stack Overflow用户

发布于 2017-05-16 11:38:10

这是一个有用的密码。还要验证证书是否有效。我推荐您使用RayWenderlich屏幕的ios10通知。

更改标题和正文以及lastone后,尝试删除contentHandler

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

    if let bestAttemptContent = bestAttemptContent {
        var attachmentString = ""

        if let bigImage = bestAttemptContent.userInfo["gcm.notification.bigImage"] as? String {
            attachmentString = bigImage
        }

        if attachmentString != "", let attachmentUrl = URL(string: attachmentString)
        {
            let session = URLSession(configuration: URLSessionConfiguration.default)
            let attachmentDownloadTask = session.downloadTask(with: attachmentUrl, completionHandler: { (url, response, error) in
                if let error = error {
                    print("Error downloading attachment: \(error.localizedDescription)")
                } else if let url = url {
                    let attachment = try! UNNotificationAttachment(identifier: attachmentString, url: url, options: [UNNotificationAttachmentOptionsTypeHintKey : kUTTypePNG])
                    bestAttemptContent.attachments = [attachment]
                }
                contentHandler(bestAttemptContent)
            })
            attachmentDownloadTask.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)
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43999882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档