70
65

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOS でプッシュ通知から起動したときのハンドリング

Posted at

たとえば、リモートプッシュを受け取ったら、ペイロードに記載の url を webview で開くために presentViewController したい、みたいなとき。

NSNotificationQueue で通知を遅延させる

NSNotificationCenter の postNotification だと、メインの ViewController が observer になる前に notification が伝搬しちゃう。
なので、NSNotificationQueue Class Reference にあるように、NSNotificationQueue を使って遅延させる。

AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if ( userInfo ) {
        NSNotification *notification = [NSNotification notificationWithName:@"HogeNotification"
                                                                     object:self
                                                                   userInfo:userInfo];
        NSNotificationQueue *queue = [NSNotificationQueue defaultQueue];
        [queue enqueueNotification:notification postingStyle:NSPostWhenIdle];
    }

    // do something...
}

メインとなる ViewController で observe する

MainViewController.pm
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self
                           selector:@selector(handleRemotePush:)
                               name:@"HogeNotification"
                             object:nil];

    // do something...
}
- (void) handleRemotePush:(NSNotification *)notification {
    NSURL *url = [NSURL URLWithString:notification.userInfo[@"url"] ];

    // show the url in web view...
}

プッシュ通知からの起動をデバッグする

ふつうに Run するとアプリ起動しちゃうし、かといって終了させるとデバッガも終了しちゃうし詰むので、以下のようにする。

  • Edit Scheme -> Info タブ -> Launch を Automatically から Wait for Hoge.app to be launched manually へ
70
65
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
70
65

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?