ローカル通知
通知を表示する為に、初回起動時に承認を行う
通知機能を使う為には #import <UserNotifications/UserNotifications.h> が必要となる。
AppDelegate.m #import <UserNotifications/UserNotifications.h> - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //初回起動時、ユーザーの承認を得る UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted){ NSLog(@"承認された"); }else{ NSLog(@"承認されなかった"); } }]; }
通知を行う例
// 通知の表示 -(void)alertlocaNotification{ UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init]; content.title = [NSString localizedUserNotificationStringForKey:@"Hello!" //通知のタイトル(太字で表示される) arguments:nil]; content.body = [NSString localizedUserNotificationStringForKey:@"Hello_message_body" //通知のメッセージ(通常の文字で表示される) arguments:nil]; //content.sound = [UNNotificationSound defaultSound]; //通知の時、サウンドを鳴らすなら、有効にする // Deliver the notification in five seconds. UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 //何秒後に表示するか? repeats:NO]; //繰り返し通知するか? UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"TEST_ALERT_ID" content:content trigger:trigger]; // Schedule the notification. UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter]; [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { }]; }
この例では、アプリがバックグランド状態でないと、通知されない。
フォアグランドでも表示させる方法もあるようだが、ViewControllerを指定する必要があるようだ。
参考
iOS 10 時代の Notification - Qiita