快速实现APNS

2016-11-28  本文已影响62人  75dfd512edfa

本文为新手提供快速集成APNS,不为底层实现做赘诉
此集成总结来说分为三步:
1.注册通知
2.接收token
3.接收通知
一.注册通知的方法

//注册远程通知
    if ([[UIDevice currentDevice].systemVersion floatValue] < 8.0)
    {
        UIRemoteNotificationType type = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound;
        
        [application registerForRemoteNotificationTypes:type];
        
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:type categories:nil];
        
        [application registerUserNotificationSettings:setting];
        
    }
#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //register to receive notifications
    [application registerForRemoteNotifications];
}
#endif

二.接收token


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString* newToken = [[[NSString stringWithFormat:@"%@",deviceToken]
                           stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]] stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"nsdata:%@\n 字符串token: %@",deviceToken, newToken);// 获取device token
    //将token发送给服务器
    
    //将token存到本地
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:newToken forKey:@"deviceToken"];
    [defaults synchronize];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"RegistFail %@",error);
}

三.接收消息

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"userInfo===%@",userInfo);
}

总结:个人认为在开发中需要注意的是:需要ios给服务器提供相应的推送证书(在开发者中心创建,本文不作详细说明)。Xcode8之后尤其注意此处应打开,否则会接收不到token


上一篇 下一篇

猜你喜欢

热点阅读