来自通知附件网址

时间:2018-03-30 16:28:10

标签: ios swift image notifications remote-notifications

我想通过此网址初始化图片:

文件:///var/mobile/Library/SpringBoard/PushStore/Attachments/username.com.NotificationApp/110278d44fc11178281b4adee06017316484b6d8.jpeg

此网址是在UNNotificationServiceExtension:

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

        if let bestAttemptContent = bestAttemptContent {

            if let attachmentURL = request.content.userInfo["attachment-url"] as? String, let fileUrl = URL.init(string: attachmentURL) {
                URLSession.shared.downloadTask(with: fileUrl, completionHandler: { (location, response, error) in
                    if let error = error {
                        print(error)
                        return
                    }
                    if let location = location {

                        let tmpDirectory = NSTemporaryDirectory()
                        let tmpFile = "file://".appending(tmpDirectory).appending(fileUrl.lastPathComponent)
                        let tmpUrl = URL(string: tmpFile)!

                        try! FileManager.default.moveItem(at: location, to: tmpUrl)

                        if let attachment = try? UNNotificationAttachment(identifier: "", url: tmpUrl) {
                            self.bestAttemptContent?.attachments = [attachment]
                        }
                    }
                    self.contentHandler!(self.bestAttemptContent!)
                }).resume()
            } else {
                self.contentHandler!(self.bestAttemptContent!)
            }
        }
    }

现在,在Notification Content Extension中我尝试初始化图像但它失败了:

class NotificationViewController: UIViewController, UNNotificationContentExtension {

    @IBOutlet var label: UILabel!
    @IBOutlet var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any required interface initialization here.
    }

    func didReceive(_ notification: UNNotification) {
        if let attachment = notification.request.content.attachments.first {
            self.imageView.image = UIImage.init(contentsOfFile: attachment.url.lastPathComponent)
        }
    }
}

0 个答案:

没有答案