OStack程序员社区-中国程序员成长平台

标题: ios - iOS 10 推送通知中的媒体附件 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 12:01
标题: ios - iOS 10 推送通知中的媒体附件

我正在为在 iOS 10 中向我的推送通知添加图像而苦苦挣扎。

我添加了通知服务扩展,并使用了以下代码:

        override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    self.contentHandler = contentHandler
    bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)


    if let urlString = request.content.userInfo["image-url"] as? String, let fileUrl = URL(string: urlString) {
        URLSession.shared.downloadTask(with: fileUrl) { (location, response, error) in
            if let location = location {
                let options = [UNNotificationAttachmentOptionsTypeHintKey: kUTTypePNG]
                if let attachment = try? UNNotificationAttachment(identifier: "", url: location, options: options) {
                    self.bestAttemptContent?.attachments = [attachment]
                }
            }
            self.contentHandler!(self.bestAttemptContent!)
            }.resume()
    }
}

我从下面的第一个答案中得到了这段代码。

我现在遇到的问题是收到了通知,有一个短暂的延迟,表明下载一定在进行,但没有显示附件。

我假设正在调用 serviceExtensionTimeWillExpire() 并且只显示 bestAttempt

非常感谢任何帮助。

我相信我的 APNs 负载配置正确,我相信:

apns: {
  aps: { 
    alert: { 
      title: "Title", 
      subtitle: "Subtitle", 
      body: "Body"
    }, 
    "mutable-content": 1
  },
  "image-url": "https://helloworld.com/image.png" 
}



Best Answer-推荐答案


您必须从通知的用户信息中提取 url,然后下载图像并为附件提供文件 url。尝试类似的东西:

if let urlString = request.content.userInfo["image-url"] as? String, let fileUrl = URL(string: urlString) {
    URLSession.shared.downloadTask(with: fileUrl) { (location, response, error) in
        if let location = location {
            let options = [UNNotificationAttachmentOptionsTypeHintKey: kUTTypePNG]
            if let attachment = try? UNNotificationAttachment(identifier: "", url: location, options: options) {
                self.bestAttemptContent.attachments = [attachment]
            }
        }

        self.contentHandler(self.bestAttemptContent)
    }.resume()
}  

关于ios - iOS 10 推送通知中的媒体附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399154/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4