【发布时间】:2020-07-06 17:59:44
【问题描述】:
我无法让 Firebase 推送通知使用图像来工作。我通过 FCM 接口发送有效载荷。当我使用图像链接填写“通知图像”字段时,在我的设备上进行测试时图像无法通过。
推送通知已成功发送到我的手机,但图像从未出现。
我已经设置了通知服务扩展。非常感谢任何帮助。
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()
}
}
【问题讨论】:
-
请显示您发送到 fcm 的有效负载
-
有效载荷必须与firebase documentation中指示的相同
-
我通过 FCM 添加了我的推送设置的屏幕截图。
标签: swift push-notification firebase-cloud-messaging