LoginSignup
1
4

More than 5 years have passed since last update.

ローカルプッシュ通知(iOS10以降)

Posted at

普段は、外部サーバーなどと連携したリモートプッシュ通知を使う機会が多いですが、
今回は、ローカルプッシュ通知の機能に少し触れてみました。
※iOS10から実装されたUser Notifications Frameworkを使ってみました。

ユーザーの通知使用許可をとる

AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    if ( floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_9_x_Max )
    {
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:
         (UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert ) completionHandler:^(BOOL granted, NSError *_Nullable error) {
             if (granted) {
             }
         }];
        // デリゲートを接続
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;

        [application registerForRemoteNotifications];

    } else {
        // iOS9以前の場合
        NSLog(@"iOS9以前の端末です。");
    }
    return YES;
}

ローカルプッシュ通知の登録

おそらく、以下で「ボタンを押下後、通知を受ける」ことが可能

ViewController.m
// 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];
}

まとめ

通知する内容、タイミング次第では、外部サーバーを使用しないローカルプッシュ通知でも十分要件を満たせることが多そうだと感じました。
通常の通知以外にも、「アクションボタン付き通知」や「位置情報を基にした通知」などもあるみたいなので、少しずつ触れていきたいです。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4