毎度のことながら自分用の劣化コピー備忘録ブログです。
自分がメインで手を入れているアプリはObjective-Cで作って徐々にSwiftに置き換わっています。
そんな中でlocalNotificationがiOS10以降でdepricatedになりUNUserNotificationCenterを推奨されたので調べてみました。
参考サイト
Xcode|iOS10で新しくなったUNUserNotificationCenterの使い方を調べてみた
ローカルプッシュ通知(iOS10以降) – Qiita
[iOS 10] User Notifications framework を使用してリモート通知を受け取る処理を実装する #wwdc | DevelopersIO
まずUNUserNotificationCenterを使う前提としてUserNotifications.frameworkが必要です。
入れておきましょう。
とりあえず未だ、AppDelegateはObjective-CなんでObjective-Cで書きます。
まずはUserNotificationをインポートしてデリゲートをセットします。
1 2 3 4 5 6 7 |
~略~ #import "AppDelegate.h" @import UserNotifications; @interface AppDelegate ()<UIApplicationDelegate,UNUserNotificationCenterDelegate> { ~略~ |
次にUNUserNotificationCenterのユーザーに対する許諾をもらう部分です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. //バッジ、サウンド、バナーの許可を求める。 [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert ) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { // APNSはここで設定するの? } }]; [UNUserNotificationCenter currentNotificationCenter].delegate = self; // [application registerForRemoteNotifications];//これはリモート通知の場合に要るのかな? |
以上でアプリがバックグランドの時はローカル通知を受けれますが、フォアグラウンドでも通知が受けれるようにするには下記のメソッドを追加します。
1 2 3 4 5 6 7 |
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { // アプリがフォアグランドにいた場合の通知動作を指定する。 completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert); }; |
viewControllerはほぼSwiftに置き換わってるのでObjective-Cでのテストはしていません。
以下は参考サイトからのコピペですすみません。
多分動くと思います。(-人-)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// UserNotificationsのインポートが必要 - (IBAction)push:(id)sender { // 通知を作成 UNMutableNotificationContent *unMutableNotice = [UNMutableNotificationContent new]; // title、body、soundを設定 unMutableNotice.title = @"おはようございます"; unMutableNotice.body = @"今日も一日頑張ってください!"; unMutableNotice.sound = [UNNotificationSound defaultSound]; // 通知タイミングを設定(今回は、実装後5秒後に通知を受信します) UNTimeIntervalNotificationTrigger *triger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; // リクエストの作成 UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"リクエスト" content:unMutableNotice trigger:triger]; // NUserNotificationCenterにリクエストを投げる [UNUserNotificationCenter.currentNotificationCenter addNotificationRequest:request withCompletionHandler:nil]; } |