LoginSignup
23

More than 5 years have passed since last update.

アプリが起動されてない場合のPush通知からの起動動作について

Last updated at Posted at 2016-08-02

はじめに

プッシュ通知の話をする前にアプリの状態について

状態 概要
Active アプリがフォアグラウンドであり操作が可能な状態
Inactive バックグラウンドからフォアグラウンドに復帰した直後や、通知センター、CCセンターにアプリが覆われている状態
Background アプリが背面にありホーム画面や他のアプリが全面に表示されている状態

プッシュ通知受け取り後に何らかの動作をさせる

アプリが生きている状態

AppDelegate.m
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    switch (application.applicationState) {
        case UIApplicatoinStateActive:
            NSLog(@"フォアグラウンドでご飯が炊けました♪");
            break;
        case UIApplicationStateInActive:
            NSLog(@"非アクティブ状態でご飯が炊けました♪");
            break;
        case UIApplicationStateBackground:
            NSLog(@"バックグラウンドでご飯が炊けました♪");
            break;
        default:
            NSLog(@"よくわからないけどご飯が炊けました♪");
    }
}

また、 userInfo に設定したJSONが入っているのでいい感じにパースしましょう!

サンプルJSONデータ
{
    "aps": {
        "alert": {
            "subject": "小泉花陽ちゃんからのメッセージです",
            "message": "ご飯炊けたよォォ!!!",
            "sound": "default",
            "badge": 1
        },
        "uri": "app-callback://messages/hanayo"
    }
}

アプリがキルされている状態

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    _userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    if (_userInfo) {
        NSLog(@"ご飯をよそえました!!");
    }
    return YES;
}

また、ここではプッシュ通知からの起動でモーダルや画面遷移をさせるなどの動作を必要とするためプロパティで別途 userInfo を作っています。

ViewController.m
// 画面遷移サンプル
AppDelegate *delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
if (delegate.userInfo) {
    // URLスキーマで遷移先を決定するなどのhogehoge動作
    NSString *scheme = userInfo[@"uri"];
    // hogehogeした
    MessageViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"MessageViewController"];
    controller.message = userInfo[@"alert"][@"message"];
    [self.navigationController pushViewController:controller animated:YES];
}

おまけ

PythonでiOSアプリにプッシュ通知を送ろう
この記事でプッシュ通知テストとかしてみてはどうでしょうか!!

小泉花陽ちゃん可愛いですよね!

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
23