標籤:
首先,在AppDelegate.m 中:
1,註冊通知
//[objc] view plaincopyprint?在CODE上查看代碼片派生到My 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) { //如果應用程式訊息通知標記數(即小紅圈中的數字)大於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=0; 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。
iOS:APNS推送主要代碼