UserNotifications について

時計とアラームをアプリに組み込んでいて、時間が来たら Alerm を出すわけですが、以前は、Notification とか使っていたんですけど、いつの間にか、UNNotificationCenter なる Framework が追加になっていた。

Swift ベースの記述が多くて難儀しましたが、いろいろ調べたところ、今までよりも格段に使いやすくなっていることが分かりました。後学のため、組み込み方をメモします。

以下のような記述が必要ですが、ひとまずは Appdelegage.m の applicationDidFinishLaunchingWithOptions に記載。

    //set NotificationCenter instance

    UNUserNotificationCenter* notificationCenter = [UNUserNotificationCenter currentNotificationCenter];

    

    // set delegate

    notificationCenter.delegate = self;

    

    //setting type of notification

    // use Sound and Alert

    [notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionSound|UNAuthorizationOptionAlert

                                      completionHandler:^( BOOL granted, NSError * _Nullable error )

     {

         // none

     }];

 

 

フォアグラウンドで通知を受けた場合の処理は delegate method が呼ばれる。

該当するクラスに、delegate を設定し、.delegate = self; を忘れずに、以下のメソッドを記入。

 

 

- (void) userNotificationCenter:(UNUserNotificationCenter *)center

        willPresentNotification:(UNNotification *)notification

          withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler

{

 

    // アプリがフォアグランドにいた場合の通知動作を指定する。

    completionHandler(UNNotificationPresentationOptionBadge |

                      UNNotificationPresentationOptionSound |

                      UNNotificationPresentationOptionAlert);

}

 

はまってしまったのは、AppDelegate.m に記載しなければならないのかと思ったのですが、普通に delegate method だったので、delegate の宣言をして、呼んで欲しいクラスに書けば OK。