Apple公司里的推送相比安卓真的很简单,因为系统已经完全通过ASPN实现好了。废话不多具体代码:
iOS 实现推送要实现三段代码。
第一段:在AppDelegate里的,
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 获取系统版本号
double version = [[UIDevice currentDevice].systemVersion doubleValue];//判定系统版本。
if(version>=8.0f){
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[application registerForRemoteNotifications];
}else{
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
}
}将这段代码粘贴过去就OK了。
第二段:给AppDelegate添加两个方法,
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
//保存token到用户默认设置中
NSUserDefaults *userDefault =[NSUserDefaults standardUserDefaults] ;
[userDefault setValue:token forKey:@"gjxq_token"];
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
}
当你的应用收到苹果返回的Token,会调用第一个方法;如果失败,则会调用第二个方法。