我无法使用镜像获取Firebase推送通知。我正在通过FCM接口发送有效载荷。当我使用图像的链接填写"Notification Image“字段时,该图像在我的设备上测试时无法通过。
推送通知已成功发送到我的手机,但图像从未出现。
我已经设置了通知服务扩展。任何帮助都是非常感谢的。
import UserNotifications
import FirebaseMessaging
import Foundation
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)
guard let bestAttemptContent = bestAttemptContent,
let attachmentUrlAsString = bestAttemptContent.userInfo["url"] as? String,
let attachmentUrl = URL(string: attachmentUrlAsString) else {
return
}
let mediaInfo = bestAttemptContent.userInfo
Messaging.serviceExtension().populateNotificationContent(bestAttemptContent, withContentHandler: contentHandler)
print("media info for push is: \(mediaInfo)")
downloadImageFrom(url: attachmentUrl) { (attachment) in
if let attachment = attachment {
bestAttemptContent.attachments = [attachment]
contentHandler(bestAttemptContent)
Messaging.serviceExtension().populateNotificationContent(bestAttemptContent, withContentHandler: contentHandler)
}
}
}
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)
}
}
}
extension NotificationService {
private func downloadImageFrom(url: URL, with completionHandler: @escaping (UNNotificationAttachment?) -> Void){
let task = URLSession.shared.downloadTask(with: url) { (downloadedUrl, response, error) in
//1. Test url and escape if url has problem
guard let downloadedUrl = downloadedUrl else {
completionHandler(nil)
return
}
//2.
var urlPath = URL(fileURLWithPath: NSTemporaryDirectory())
let uniqueUrlEnding = ProcessInfo.processInfo.globallyUniqueString + ".jpg"
urlPath = urlPath.appendingPathComponent(uniqueUrlEnding)
try? FileManager.default.moveItem(at: downloadedUrl, to: urlPath)
do {
let attachment = try UNNotificationAttachment(identifier: "picture", url: urlPath, options: nil)
completionHandler(attachment)
} catch {
completionHandler(nil)
}
}
task.resume()
}
}

发布于 2020-10-05 23:30:55
我是这样解决的,适用于Firebase:
guard let bestAttemptContent = bestAttemptContent,
let fcmOptions = bestAttemptContent.userInfo["fcm_options"] as? [String: Any],
let attachmentUrlAsString = fcmOptions["image"] as? String,
let attachmentUrl = URL(string: attachmentUrlAsString) else {
return
}https://stackoverflow.com/questions/62761830
复制相似问题