しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

User Notifications frameworkでローカル通知を送ってみる

iOS10から使えるようになったUser Notifications frameworkを試してみました。

通知の許可を得る

まずはXcodeにUser Notifications frameworkを追加します。

f:id:llcc:20170327230711p:plain

許可を得る処理は以下の通りです。
引数で使いたいオプションを指定します。

UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound], completionHandler: { result, error in
})

f:id:llcc:20170327231050p:plain

これはiOS9以前での以下の書き方に相当します。

let settings = UIUserNotificationSettings(types: [.badge, .alert, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)

通知を作成する

通知の作成は以下の通りです。
今回は10秒後に起動する通知を作成しました。

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)

f:id:llcc:20170327232051p:plain

上ではTimeIntervalを使ってTriggerを作りましたが、DateComponentを使ってTriggerを作る事もできます。

let component = DateComponents(calendar: Calendar.current, year: 2017, month: 3, day: 27, hour: 23, minute: 30)
let trigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: false)

UNUserNotificationCenterにはdelegate

import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        let content = UNMutableNotificationContent()
        content.title = "たいとる"
        let component = DateComponents(calendar: Calendar.current, year: 2017, month: 3, day: 27, hour: 23, minute: 30)
        let trigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: false)
        let request = UNNotificationRequest(identifier: "Identifier", content: content, trigger: trigger)
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.add(request)
        
        return true
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        // バックグラウンドで来た通知をタップしてアプリ起動したら呼ばれる
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        // アプリがフォアグラウンドの時に通知が来たら呼ばれる
    }
}

フォアグラウンドで通知が来た時、下のようにcompletionHandlerを実行すれば通知を表示する事ができます。

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
    completionHandler([.alert, .badge, .sound])
}

f:id:llcc:20170327233403p:plain

通知のキャンセルはremoveAllPendingNotificationRequestsメソッドを使います。
removePendingNotificationRequestsメソッドでIDを指定したキャンセルも可能です。

let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests()
center.removePendingNotificationRequests(withIdentifiers: ["Identifier"])