【swift】iOSでPush通知に画像表示する実装
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通知を試す。
- テストツール(こちらを使ってみました。)
- 各種設定値とカスタムJSONを設定してPushボタンで送信です。
最初は時間がかかるので少し待ってください
- 受取った通知に画像が出ました。
- 通知を下にドラッグすると画像を大きくすることが出来ます。