User Notifications frameworkではローカル通知に画像を添付できるようなので試してみました。
画像なしの通知を送る
まずは下記事を参考に通常の画像なしのローカル通知を送ってみます。
実装は下の通りです。
import UIKit import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound], completionHandler: { result, error in }) return true } func applicationDidEnterBackground(_ application: UIApplication) { let content = UNMutableNotificationContent() content.title = "たいとる" content.subtitle = "さぶたいとる" content.body = "ほんぶん" content.badge = NSNumber(value: 1) content.sound = UNNotificationSound.default() let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false) let request = UNNotificationRequest(identifier: "Identifier", content: content, trigger: trigger) let center = UNUserNotificationCenter.current() center.add(request) } }
アプリ起動&バックグラウンドに移動で下のように通知が送られます。
画像付き通知を送る
次は画像付きの通知を送ります。
まずはプロジェクトに画像を追加します。
次にローカル通知に画像を設定します。
通知を送る処理を下のように修正します。
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func applicationDidEnterBackground(_ application: UIApplication) { let content = UNMutableNotificationContent() content.title = "たいとる" content.body = "ほんぶん" if let path = Bundle.main.path(forResource: "image", ofType: "png") { content.attachments = [try! UNNotificationAttachment(identifier: "ID1", url: URL(fileURLWithPath: path), options: nil)] } let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false) let request = UNNotificationRequest(identifier: "Identifier", content: content, trigger: trigger) let center = UNUserNotificationCenter.current() center.add(request) } }
今回追加した下の部分が画像の付与処理になります。
UNMutableNotificationContentのattachmentsプロパティーに渡す事で画像を表示しています。
if let path = Bundle.main.path(forResource: "image", ofType: "png") { content.attachments = [try! UNNotificationAttachment(identifier: "ID1", url: URL(fileURLWithPath: path), options: nil)] }
この状態でアプリ起動&バックグラウンドに移動をすると下のように画像付き通知が送信されます。
UNNotificationAttachmentには動画を指定することもできます。
if let path = Bundle.main.path(forResource: "movie", ofType: "mov") { content.attachments = [try! UNNotificationAttachment(identifier: "ID1", url: URL(fileURLWithPath: path), options: nil)] }
動画は事前にプロジェクトに追加したものを使います。
この状態で通知を開くとしたのように動画を見ることができます。
画像・動画だけでなくサウンドも添付する事ができます。
if let path = Bundle.main.path(forResource: "sound", ofType: "wav") { content.attachments = [try! UNNotificationAttachment(identifier: "ID1", url: URL(fileURLWithPath: path), options: nil)] }
表示は下の通りです。