首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在iOS中通过推送通知发送图像

在iOS中通过推送通知发送图像
EN

Stack Overflow用户
提问于 2019-12-05 08:44:52
回答 1查看 2.8K关注 0票数 1

根据文档,我添加了NotificationExtension。这是代码

代码语言:javascript
复制
import UserNotifications
import Firebase
import FirebaseMessaging

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...
            bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"

            //contentHandler(bestAttemptContent)
        }

        Messaging.serviceExtension().populateNotificationContent(self.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)
        }
    }
}

firebase控制台显示图像。

但是,在调试didReceive中,从未调用或接收到的通知具有映像,即使是在iPhone设置中将通知设置为持久的通知。

要解决这个问题需要做些什么?如何查看NotificationService是否正确地连接到我的应用程序

[

代码语言:javascript
复制
AnyHashable("google.c.a.ts"): 1575541521, AnyHashable("aps"): {
    alert =     {
        body = "Test for imge";
        title = Test;
    };
    "mutable-content" = 1;
    sound = default;
}, AnyHashable("google.c.a.e"): 1, AnyHashable("google.c.a.c_l"): Data, AnyHashable("fcm_options"): {
    image = "https://thevowapp.com/iphoneapp/peri/media/portstar.png";
}, AnyHashable("gcm.notification.sound2"): default, AnyHashable("google.c.a.udt"): 0, AnyHashable("gcm.n.e"): 1, AnyHashable("gcm.message_id"): 1575541521949602, AnyHashable("google.c.a.c_id"): 5702933232519496714]

添加通知也扩展,但我没有看到任何后台模式atm,所以他们是不需要的,因为代码还没有。调试器仍然不会滚动。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-05 10:08:16

首先,通知有效负载应该在mutable-content中包含参数aps

这个参数很重要。 如果在aps中不存在,那么您的NotificationService将不会被调用,您也不会在通知的右侧获得图像。

来自这里文档

可变内容: Int 通知服务应用程序扩展标志。如果值为1,则系统在传递之前将通知传递给通知服务应用程序扩展。使用您的扩展修改通知的内容。

其次,您需要在notificationService中下载图像并将其附加到通知中。

您可以使用下面的示例作为起点。这取决于如何在有效载荷中发送图像链接。如果你会张贴你的实际有效载荷,那么我可以编辑我的文章。

代码语言:javascript
复制
import UserNotifications
import Foundation
import SwiftyJSON

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 {
            let apsData = request.content.userInfo["aps"] as! [String : Any]
            let alertData = apsData["alert"] as! [String : Any]
            let imageData = request.content.userInfo["fcm_options"] as! [String : Any]
            bestAttemptContent.title = (alertData["title"] as? String) ?? ""
            bestAttemptContent.body = (alertData["body"] as? String) ?? ""

            guard let urlImageString = imageData["image"] as? String else {
                contentHandler(bestAttemptContent)
                return
            }
            if let newsImageUrl = URL(string: urlImageString) {

                guard let imageData = try? Data(contentsOf: newsImageUrl) else {
                    contentHandler(bestAttemptContent)
                    return
                }
                guard let attachment = UNNotificationAttachment.saveImageToDisk(fileIdentifier: "newsImage.jpg", data: imageData, options: nil) else {
                    contentHandler(bestAttemptContent)
                    return
                }
                bestAttemptContent.attachments = [ attachment ]
            }
            Messaging.serviceExtension().populateNotificationContent(self.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)
        }
    }
}

//MARK: Extension for Notification Attachment
extension UNNotificationAttachment {

    static func saveImageToDisk(fileIdentifier: String, data: Data, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
        let fileManager = FileManager.default
        let folderName = ProcessInfo.processInfo.globallyUniqueString
        let folderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(folderName, isDirectory: true)

        do {
            try fileManager.createDirectory(at: folderURL!, withIntermediateDirectories: true, attributes: nil)
            let fileURL = folderURL?.appendingPathComponent(fileIdentifier)
            try data.write(to: fileURL!, options: [])
            let attachment = try UNNotificationAttachment(identifier: fileIdentifier, url: fileURL!, options: options)
            return attachment
        } catch let error {
            print("error \(error)")
        }

        return nil
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59191245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档