【发布时间】:2021-05-23 12:43:20
【问题描述】:
我正在尝试通过 Firebase 云消息发送推送通知,并成功发送仅针对文本的推送通知,但在发送带有图像的通知时遇到问题。我尝试了一些来自 medium 和 raywenderlich 的文档,但无法发送带有图像的通知。我在我的项目中添加了通知扩展并尝试了这段代码:
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["image"] as? String,
let attachmentURL = URL(string: attachmentURLAsString) else{
return
}
downloadImageFrom(url: attachmentURL) { (attachment) in
if let attachment = attachment {
bestAttemptContent.attachments = [attachment]
contentHandler(bestAttemptContent)
}
}
}
private func downloadImageFrom(url: URL, with completionHandler: @escaping (UNNotificationAttachment?) -> Void){
let task = URLSession.shared.downloadTask(with: url) { (downloadedUrl, response, error) in
guard let downloadUrl = downloadedUrl else{
completionHandler(nil)
return
}
var urlPath = URL(fileURLWithPath: NSTemporaryDirectory())
let uniqueURLEnding = ProcessInfo.processInfo.globallyUniqueString + ".jpg"
urlPath = urlPath.appendingPathComponent(uniqueURLEnding)
try? FileManager.default.moveItem(at: downloadUrl, to: urlPath)
do{
let attachment = try UNNotificationAttachment(identifier: "picture", url: urlPath, options: nil)
completionHandler(attachment)
}catch{
completionHandler(nil)
}
}
task.resume()
}
但仍然没有显示图像,请注意:我正在尝试从 firebase 控制台发送图像。我不知道如何找出问题或解决问题。
【问题讨论】:
-
首先要做的是一些故障排除;添加一个断点,当应用程序接收到通知时,逐行检查变量,直到您看到不正确的内容。例如,可能接收到的 URL 格式错误;您只有在检查了代码后才会知道。您也没有错误处理;例如在
downloadImageFrom中,如果downloadUrl 为nil,则代码将静默失败,您将不知道为什么。你也忽略了可能的错误downloadTask(with: url) { (downloadedUrl, response, error)等等错误,你不会知道的。
标签: ios swift firebase firebase-cloud-messaging