gpt4 book ai didi

ios - 使用 UNNotificationServiceExtension 进行丰富的远程通知

转载 作者:行者123 更新时间:2023-11-29 11:51:58 27 4
gpt4 key购买 nike

我正在尝试在 ios 10 中实现丰富的远程通知。我已经实现了这段代码。收到通知后的控件就到这里了,不知道怎么下载图片显示在通知里。提前致谢。

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

}

最佳答案

你会在你的 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

关于ios - 使用 UNNotificationServiceExtension 进行丰富的远程通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40734356/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com