:ghost:

Swift4 ローカル通知を5秒後に出す

5秒後にアプリからの通知が来るようにしたい

環境

コード

  • Appdelegate.swift
import UserNotifications

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // ....
        let center = UNUserNotificationCenter.current()
        // トリガーされている全ての通知をトリガー解除する
        center.removeAllPendingNotificationRequests();
        // 「通知を許可しますか?」ダイアログを出す
        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in if granted { print("通知許可")}
        }
        let content = UNMutableNotificationContent()
        content.title = "通知タイトル"
        content.body = "通知本文"
        content.sound = UNNotificationSound.default()
        // 5秒後に通知を出すようにする
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest(identifier: "HogehogeNotification", content: content, trigger: trigger)
        center.add(request)
        center.delegate = self
        // ....
    }
}

確認

  • アプリを起動する
  • 通知が来る
  • 🙌