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:是的,可以。有两种可能的情况。如果您的应用程序未运行,您将在 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 委托“确定/取消”按钮单击。
- (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,而该 devToken 需要位于您的服务器上才能向该用户发送推送通知。如果用户最初接受但后来更改设置以禁用您的推送通知,则 Apple 服务器将不会向该用户发送您的推送通知。在这种情况下,用户的 UDID 将出现在反馈服务中,理想情况下,您的服务器应从数据库中删除该用户的 UDID,并停止向该用户发送推送通知。如果您继续发送无效的推送通知,Apple 服务器可能会默默地断开您的连接,并且您将无法发送任何推送通知。
See 苹果推送通知 http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/WhatAreRemoteNotif/WhatAreRemoteNotif.html#//apple_ref/doc/uid/TP40008194-CH102-SW1文档以获取有关实施的详细信息。