【swift】iOSでPush通知に画像表示する実装

開発環境

  1. Mac OS 11.6.2
  2. Xcode 13.1

事前準備

  • Push通知を受け取る実装をしておいてください

develop-imonari.hatenablog.com

TARGETにNotification Service Extensionを追加

f:id:develop-imonari:20211228140929p:plain
f:id:develop-imonari:20211228140944p:plain
f:id:develop-imonari:20211228140956p:plain

f:id:develop-imonari:20211228163400p:plain

NotificationServiceの実装

  • TargetにNotification Service Extensionを追加するとデフォルトでNotificationService.swiftが出来上がります。
  • NotificationService.swiftのdidReceiveに画像ダウンロードと設定を行うことで、受取ったPush通知に画像が表示されます。
  • 取り出す要素名はJSONと同じにしなければならないので後述を参照してください
// プッシュ通知が届いたらこのメソッドにコールバックされます。
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    self.contentHandler = contentHandler
    bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
    // プッシュ通知のペイロードからUserInfo部分を取り出す
    if let attachment = request.content.userInfo["rpr_attachment"] as? [String: String] {
        // ペイロードに要素があれば取得
        if let urlString = attachment["url"], let fileURL = URL(string: urlString), let type = attachment["type"] {
            // urlはファイルパス。typeは拡張子
            // ペイロードのrpr_attachmentのurlからファイルをダウンロードする
            URLSession.shared.downloadTask(with: fileURL) { (location, response, error) in
                if let location = location {
                    let fileName = UUID().uuidString + "." + type
                    let tmpFile = "file://".appending(NSTemporaryDirectory()).appending(fileName)
                    let tmpUrl = URL(string: tmpFile)!
                    try? FileManager.default.moveItem(at: location, to: tmpUrl)
                    if let attachment = try? UNNotificationAttachment(identifier: "IDENTIFIER", url: tmpUrl, options: nil) {
                        self.bestAttemptContent?.attachments = [attachment]
                    }
                }
                contentHandler(self.bestAttemptContent!)
            }.resume()
        }
    } else {
        contentHandler(self.bestAttemptContent!)
    }
}

Push通知を試す。

  • テストツール(こちらを使ってみました。)

github.com

  • 各種設定値とカスタムJSONを設定してPushボタンで送信です。

最初は時間がかかるので少し待ってください
f:id:develop-imonari:20211228162237p:plain

  • 受取った通知に画像が出ました。

  • 通知を下にドラッグすると画像を大きくすることが出来ます。