A1:いいえ、アプリの起動時にある必要はありません。コード内のどこからでもregisterForRemoteNotificationTypesを呼び出すことができます。
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
プッシュ通知の登録の成功/失敗時に呼び出される次のデリゲートメソッド(デリゲート内)を処理する必要があります。
// Delegation methods
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
const void *devTokenBytes = [devToken bytes];
self.registered = YES;
[self sendProviderDeviceToken:devTokenBytes]; // this will send token to your server's database
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(@"Error in registration. Error: %@", err);
}
A2:はい、できます。考えられるシナリオは2つあります。アプリケーションが実行されていない場合は、didFinishLaunchingWithOptionsでプッシュ通知を処理します。この場合、ユーザーがメッセージアラートで[開く]を選択するか、バナーをクリックすると(ユーザーの設定によって異なります)、アプリケーションが自動的に起動し、プッシュ通知で渡されたユーザーパラメーターを処理できます。
/* Push notification received when app is not running */
NSDictionary *params = [[launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"] objectForKey:@"appsInfo"];
if (params) {
// Use params and do your stuffs
}
アプリケーションがすでに実行されている場合、プッシュ通知はapplication:didReceiveRemoteNotification:
デリゲートメソッドに配信されます。このメソッドでは、プッシュ通知でメッセージをUIAlertViewに表示し、alertViewデリゲートの[OK]/[キャンセル]ボタンのクリックを標準的な方法で処理できます。
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSDictionary *apsInfo = [userInfo objectForKey:@"apsinfo"]; // This appsInfo set by your server while sending push
NSString *alert = [apsInfo objectForKey:@"alert"];
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
application.applicationIconBadgeNumber = 0;
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"Push Notification"
message:alert
delegate:self
cancelButtonTitle:@"NO"
otherButtonTitles:@"YES"];
[alertview show];
[alertview release];
} else {
[self setTabs:contentsInfo];
}
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex != [alertView cancelButtonIndex]) {
// User pressed YES, do your stuffs
}
}
A3:ユーザーがアプリからのプッシュ通知の受け入れを拒否した場合、そのdidFailToRegisterForRemoteNotificationsWithErrorが発生するため、そのユーザーにプッシュ通知を送信するためにサーバー上に必要なユーザーのdevTokenを取得できません。ユーザーが最初に承諾したが、後でプッシュ通知を無効にするように設定を変更した場合、Appleサーバーはそのユーザーにプッシュ通知を送信しません。この場合、そのユーザーのUDIDはフィードバックサービスに表示されます。理想的には、サーバーはそのユーザーのUDIDをデータベースから削除し、今後そのユーザーへのプッシュ通知の送信を停止する必要があります。無効なプッシュ通知を送信し続けると、Appleサーバーがサイレントに接続を切断し、プッシュ通知を送信できなくなる可能性があります。
実装の詳細については、Appleプッシュ通知のドキュメントを参照してください。