真机环境,推送要证书和配置文件,app id中bundle id必须和程序中的一致,三种形式:锁屏、解锁情况下运行其他程序、这个程序正在运行
1.在oc中:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//注册推送
if ([[[UIDevicecurrentDevice]systemVersion]floatValue]<8.0) {
[[UIApplicationsharedApplication]registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound) ];
}else{//下面两个方法都要写
[[UIApplicationsharedApplication]registerForRemoteNotifications];
[[UIApplicationsharedApplication]registerUserNotificationSettings:[UIUserNotificationSettingssettingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSoundcategories:nil]];
}
NSDictionary *pushNotificationKey = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (pushNotificationKey) {//这里处理推送消息
UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"推送通知"message:@"这是推送窗口打开的程序,你可以在这里处理推送内容"delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil,nil];
[alertshow];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{//注册成功会调用的
NSString *tokenString = [deviceToken description];
NSLog(@"apns--->生成的token=%@",tokenString);
要把这个值去掉<>后传给服务器- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(@"apns-->注册推送时发生错误,信息是:%@",error);
失败后会调用一般是(测试的时候遇到问题 未找到应用程序的“aps-environment”的权利字符串"),appid中bundle id不一致或是证书选错<有推送功能的appid,单击edit,下载那里面的证书>
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
NSLog(@"%s %s 推送的消息:%@",__FILE__,__FUNCTION__, userInfo);
application.applicationIconBadgeNumber =0;
if ([[userInfo objectForKey:@"aps"]objectForKey:@"alert"]!=NULL) {
UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@""message:[[userInfo objectForKey:@"aps"]objectForKey:@"alert"]delegate:selfcancelButtonTitle:@"关闭"otherButtonTitles:@"处理推送消息",nil];
[alertshow];
UIApplication.sharedApplication().registerForRemoteNotifications()
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert|UIUserNotificationType.Badge|UIUserNotificationType.Sound, categories: nil))