IOS 一个信号通知中的图像

image in IOS onesignal notification

我怎样才能创建像这样的通知 IOS notification with image

据说IOS不能指定icon,但是这个app是怎么做到的呢?

我试过 ios_attachments,small_icon,large_icon,big_picture 但我没有按预期回答

您可以使用 Notification Service Extension 用于带图像的推送通知。这是 iOS10 的一项新功能。更多详情 here.

步骤:

  1. 在推送通知的负载中指定图像 URL,如下所示:

    {
        "aps" : {
            "alert" : "You got your emails.",
            "badge" : 9,
            "sound" : "bingbong.aiff"
        },
        "image_url" : "http://host_name/image.png",
    }
    
  2. 发送推送通知

  3. 收到推送通知后,Notification Service Extension在显示通知横幅之前被激活,所以使用URL中的URL下载图像并存储在tmp区域有效载荷

  4. 将显示带有图像的通知

实施 Notification Service Extension

  1. 添加Notification Service Extension

    • File > New > Target 在 Xcode 菜单中

  • iOS > Application Extension > Notification Service Extension

  • NotificationService.swift 已创建。

  1. 实施func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void)

这里是代码示例:

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

    guard let imageUrl = request.content.userInfo["image_url"] as? String else {
        if let bestAttemptContent = self.bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
        return
    }

    let session = URLSession(configuration: URLSessionConfiguration.default)
    let task = session.dataTask(with: URL(string: imageUrl)!, completionHandler: { (data, response, error) in
        do {
            if let tempImageFilePath = NSURL(fileURLWithPath:NSTemporaryDirectory())
                .appendingPathComponent("tmp.jpg") {
                try data?.write(to: tempImageFilePath)

                if let bestAttemptContent = self.bestAttemptContent {
                    let attachment = try UNNotificationAttachment(identifier: "id", url: tempImageFilePath, options: nil)
                    bestAttemptContent.attachments = [attachment]
                    contentHandler(bestAttemptContent)
                }
            } else {
                // error: writePath is not URL
                if let bestAttemptContent = self.bestAttemptContent {
                    contentHandler(bestAttemptContent)
                }
            }
        } catch _ {
            // error: data write error or create UNNotificationAttachment error
            if let bestAttemptContent = self.bestAttemptContent {
                contentHandler(bestAttemptContent)
            }
        }
    })
    task.resume()
}

这使您的应用能够从 image _ url 的有效负载中下载图像并将其附加到推送通知。