簡體   English   中英

IOS onesignal通知中的圖片

[英]image in IOS onesignal notification

如何創建帶有圖像的IOS通知之類的通知

據說您不能為IOS指定圖標,但是此應用程序是如何做到的?

我嘗試了ios_attachments,small_icon,large_icon,big_picture,但未按預期回答

您可以將Notification Service Extension用於帶圖像的Push Notification。 這是iOS10的新功能。 這里有更多細節。

腳步:

  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將圖像下載並存儲在tmp區域中

  4. 顯示帶有圖像的通知

實施 Notification Service Extension

  1. 添加Notification Service Extension

    • Xcode菜單中的File > New > Target

在此處輸入圖片說明

  • 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下載圖像並將其附加到推送通知中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM