ios10のローカル通知 〜通知削除
UNUserNotificationCenterを使って複数のローカル通知登録した場合に、
コメントアウト&ビルドした後もコメントアウト前に登録した通知情報が残る&通知される。
mport UIKit import UserNotifications class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound]){ (granted, error)in } //バックグラウンドで60秒ごとに通知登録 let content = UNMutableNotificationContent() content.title = "ローカル通知確認60s" content.body = "ローカル通知確認60s!!!!!!" content.sound = UNNotificationSound.default() let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (60), repeats: true) let requestIdentifier = "60sTrigger" let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger) center.add(request) //下記をコメントアウトしても一度でも登録した場合にコメントアウト後にも通知されてしまう。 //バックグラウンドで70秒ごとに通知登録 //let content70 = UNMutableNotificationContent() //content70.title = "ローカル通知確認70" //content70.body = "ローカル通知確認70!!!!!!" //content70.sound = UNNotificationSound.default() //let trigger70 = UNTimeIntervalNotificationTrigger(timeInterval: (70), repeats: true) //let requestIdentifier70 = "70sTrigger" //let request70 = UNNotificationRequest(identifier: requestIdentifier70, content: content70, trigger: trigger70) //center.add(request70)
そんな時は通知情報を削除するremoveAllPendingNotificationRequestsを実行すると通知前の情報は全て削除される。
identifierを指定して特定の通知のみを削除するremoveDeliveredNotifications(withIdentifiers:)もある。
ios10のローカル通知
ios10から追加されたUserNotificationsを使ってローカル通知を試しに実装してみた。
ちなみにUILocalNotificationはiso10から非推奨になった。
import UIKit import UserNotifications class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //通知許可設定 let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound]){ (granted, error)in } //contentの設定 let content = UNMutableNotificationContent() content.title = "ローカル通知タイトル" content.body = "ローカル通知ボディ" content.sound = UNNotificationSound.default() //通知トリガー let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (10), repeats: false) //identifier let requestIdentifier = "sampleRequest" let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger) center.add(request) } }
通知トリガーでrepeats: true にした場合にtimeIntervalが60sより早い場合(10sとか50s)はエラーになってしまうのは不明。
特に、ドキュメントには記載されていない感じだった。
上のサンプルコードは、基本的にはUILocalNotificationでも実装できたことUserNotificationsで実装されているだけ。
アプリがバックグラウンドにいる時にローカル通知がされるから、フォアグラウンドの場合は通知されない。
フォアグラウンド状態でも通知したい場合は、別途実装が必要になる。次の機会にその辺を調査する。