【Swift】ローカル通知のバックグラウンド対応
- 4. func setupUNNotification() {
// 通知内容
let content = UNMutableNotificationContent()
content.sound = .default
content.title = "通知を受信"
content.body = "f2fwegewgewgewgewg"
// 3秒後に通知
let timeIntervalTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
// 通知のリクエスト
let request = UNNotificationRequest(identifier: UNNotificationValues.localNotificationIdentifier, content: content,
trigger: timeIntervalTrigger)
// 通知を登録
let center = UNUserNotificationCenter.current()
center.add(request) { (error: Error?) in
if let error = error {
print(error.localizedDescription)
}
}
}
ローカル通知の作成
- 5. extension AppDelegate: UNUserNotificationCenterDelegate {
// アプリ上(フォアグラウンド)で通知を受信した場合
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {}
// 通知をタップした場合
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {}
}
ローカル通知のメソッド
- 10. func sceneDidBecomeActive(_ scene: UIScene) {
// 通知された通知を全て取得
// notifications:[UNNotification]
UNUserNotificationCenter.current().getDeliveredNotifications { (notifications) in
if !notifications.isEmpty {
for notification in notifications {
// ローカル通知のプロパティを取り出せる
print(notification.request.identifier)
print(notification.request.content.title)
print(notification.request.content.body)
}
}
// 受信処理が完了したので削除
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers:
["ローカル通知のidenfier"])
}
}
- 11. func sceneWillEnterForeground(_ scene: UIScene) {
// 通知された通知を全て取得
// notifications:[UNNotification]
UNUserNotificationCenter.current().getDeliveredNotifications { (notifications) in
if !notifications.isEmpty {
for notification in notifications {
// ローカル通知のプロパティを取り出せる
print(notification.request.identifier)
print(notification.request.content.title)
print(notification.request.content.body)
}
}
// 受信処理が完了したので削除
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers:
["ローカル通知のidenfier"])
}
}