通過真機調試以下代碼:開發環境擷取的deviceToken和釋出環境擷取的deviceToken當然是不一樣的!
而且在開發環境和釋出環境中如果開發證書不一樣的話擷取的deviceToken也不一樣,親測!!!
文章末尾讨論釋出環境的deviceToken 。。。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] init];
self.window.backgroundColor = [UIColor whiteColor];
self.window.frame = [[UIScreen mainScreen] bounds];
[self registerNotification:application];
[self.window makeKeyAndVisible];
return YES;
}
- (void)registerNotification:(UIApplication *)application
{
if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8) {
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)])
{
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[application registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
}
}else
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
NSLog(@"not isIOS8");
}
}
///Token值成功擷取的時候走的是這個方法(Token值不能帶空格)
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(@"deviceToken----------->%@",deviceToken);
NSString *pushToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:@"<" withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString:@" " withString:@""] ;
NSLog(@"pushToken----------->%@",pushToken);
}
///Token值擷取失敗的時候走的是這個方法
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(@"Token值擷取失敗,error--->%@",error);
}
///應用程式處在打開狀态,且伺服器有推送消息過來時,以及通過推送打開應用程式,走的是這個方法
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
for (id key in userInfo) {
NSLog(@"%@:%@",key, [userInfo objectForKey:key]);
}
///Icon推送數量設為0
application.applicationIconBadgeNumber=0;
}
現在來讨論釋出環境的deviceToken,之前我認為是不會改變的,但後來發現貌似會變。當然這個調試就需要去回複iPhone手機了,如果你願意可以去試試,弄個不用的iPhone4,iPhone4s之類的。
if a device is wiped, it will get a new device token. (如果一個裝置被清除,它将獲得一個新的裝置令牌。)
官方網站是這樣寫的: If the user restores backup data to a new device or computer, or reinstalls the operating system, the device token changes
正是因為device有可能改變,是以官方描述:An application should register every time it launches and give its provider the current token
是以...不要判斷APP裡是否已經儲存的deviceToken 就不去register了, should every time !!
另見 iOS Push Notification注意事項