且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS 推送通知中的图片

更新时间:2023-02-26 20:47:45

这一行:

if let urlString = notificationData["attachment-url"], let fileUrl = URL(string: urlString) {

正在寻找 attachment-url 值作为 userInfo 字典中 data 对象的子对象.它正在寻找这个:

Is looking for an attachment-url value as a child of a data object in the userInfo dictionary. It is looking for this:

{ 
    "aps" : {
        ...
    },
    "data" : {
        "attachment-url" : "some url"
    }
}

但是您问题中的有效载荷是这样的:

But the payload in your question is this:

{
    "aps":{
        "sound":"default",
        "alert": {
                    "title":"iOS",
                    "body":"Hello Dude...."
                },
        "mutable-content": 1
    },
    "CustomData": {
        "mType":"alert",
        "m":"Hello Dude...."
    },
    "Attachement-url":"https://pusher.com/static_logos/320x320.png"
} 

数据"部分不存在,attachment-url 键不存在.

The "data" section does not exist, and the attachment-url key does not exist.

更改您的 Swift 代码以匹配有效负载中的内容,您应该能够获取图像 URL 并下载它.

Change your Swift code to match what is in the payload and you should be able to get the image URL and download it.

如果您收到的通知没有包含附件 URL 密钥或附件 URL 不是格式正确的 URL,那么您将遇到大问题.在这些情况下,您的 if let 不会被输入并且 contentHandler 不会被调用!这不仅会导致服务扩展锁定,还会阻止发送任何没有附件 URL 的通知!添加一个调用 contentHandlerelse 来解决这个问题.

You will have a big problem if you receive a notification that does not have the attachment URL key or the attachment URL is not a properly formed URL. In those cases your if let will not be entered and the contentHandler will not be called! This will not just cause the service extension to lock up, but it will prevent any notification that does not have the attachment URL from being delivered! Add an else that calls the contentHandler to fix this.

一旦你下载了它,虽然还有另一个问题.iOS 需要知道您在附件中放入了什么样的数据.附件选项字典允许您包含有关附件的类型信息.获取下载文件的 MIME 类型并从中创建统一类型标识符.然后可以在选项字典中使用统一类型标识符字符串.

Once you have it downloaded though there is another problem. iOS will need to know what kind of data you are putting in the attachment. The attachment options dictionary allows you to include type information about the attachment. Get the MIME Type of the downloaded file and create a Uniform Type Identifier from that. The Uniform Type Identifier string can then be used in the options dictionary.

我在 iOS 通知手册中深入介绍了所有这些内容.现在可用的示例章节涉及向通知添加图像.

I cover all of this in depth in the iOS Notifications book. The sample chapter available now deals with adding images to notifications.