首先,在AppDelegate.m 中:
1,注册通知
//[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
ViewController *mainCtrl=[[ViewController alloc] init];
self.window.rootViewController=mainCtrl; //注册通知
if ([UIDevice currentDevice].systemVersion.doubleValue<8.0) {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge)];
}
else {
[[UIApplication sharedApplication] registerForRemoteNotifications];
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil]];
} //判断是否由远程消息通知触发应用程序启动
if (launchOptions) {
//获取应用程序消息通知标记数(即小红圈中的数字)
NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
if (badge>) {
//如果应用程序消息通知标记数(即小红圈中的数字)大于0,清除标记。
badge--;
//清除标记。清除小红圈中数字,小红圈中数字为0,小红圈才会消除。
[UIApplication sharedApplication].applicationIconBadgeNumber = badge;
NSDictionary *pushInfo = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"]; //获取推送详情
NSString *pushString = [NSString stringWithFormat:@"%@",[pushInfo objectForKey:@"aps"]];
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"finish Loaunch" message:pushString delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil nil];
[alert show];
}
} return YES;
2,注册通知后,获取device token
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
NSLog(@"My token is:%@", token);
//这里应将device token发送到服务器端
} - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSString *error_str = [NSString stringWithFormat: @"%@", error];
NSLog(@"Failed to get token, error:%@", error_str);
}
3,接收推送通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
[UIApplication sharedApplication].applicationIconBadgeNumber=;
for (id key in userInfo) {
NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
}
/* eg.
key: aps, value: {
alert = "\U8fd9\U662f\U4e00\U6761\U6d4b\U8bd5\U4fe1\U606f";
badge = 1;
sound = default;
}
*/
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"remote notification" message:userInfo[@"aps"][@"alert"] delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil nil];
[alert show];
}
注意:app 前台运行时,会调用 remote notification;app后台运行时,点击提醒框,会调用remote notification,点击app 图标,不调用remote notification,没反应;app 没有运行时,点击提醒框,finishLaunching 中,launchOptions 传参,点击app 图标,launchOptions 不传参,不调用remote notification。