deviceToken的获取(一)

1.获得deviceToken的过程


 

 

1>客户端向苹果服务APNS,发送设备的UDID和英语的Bundle Identifier.
2>经苹果服务器加密生成一个deviceToken
3>将当前用户的deviceToken(用户标识),发送给自己应用的服务器
4>自己的服务器,将得到的deviceToken,进行保存

2.利用deviceToken进行数据传输,推送通知


 

5>需要推送的时候,将消息和deviceToken一起发送给APNS,苹果服务器,再通过deviceToken找到用户,并将消息发给用户


 

这里不再演示关于证书的配置, 简单的只进行说明步骤:
1> 创建明确的AppID,只有明确的AppID才能进行一些特殊的操作
2>真机调试的APNS SSL证书
3>发布程序的APNS SSL证书
4>生成描述文件
[依次安装证书, 再装描述]

注册远程推送通知:

1.客户端如果想要接收APNs的远程推送通知,必须先进行注册(得到用户授权)
一般在APP启动完毕后就马上进行注册

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
        // 1.注册UserNotification,以获取推送通知的权限
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge categories:nil];
        [application registerUserNotificationSettings:settings];

        // 2.注册远程推送
        [application registerForRemoteNotifications];
    } else {
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeNewsstandContentAvailability | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
    }

    return YES;
}

2.注册成功后, 调用AppDelegate的方法,获取到用户的deviceToken

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // <32e7cf5f 8af9a8d4 2a3aaa76 7f3e9f8e 1f7ea8ff 39f50a2a e383528d 7ee9a4ea>
    // <32e7cf5f 8af9a8d4 2a3aaa76 7f3e9f8e 1f7ea8ff 39f50a2a e383528d 7ee9a4ea>
    NSLog(@"%@", deviceToken.description);
}

3.点击推送通知,和本地一样有两种状况.
1> app没有关闭,只是一直隐藏在后台
让app进入前台, 并调用下面的方法(app没有重新启动)
过期的方法:

// 当接受到远程退职时会执行该方法(当进入前台或者应用程序在前台)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"%@", userInfo);

    UIView *redView = [[UIView alloc] init];
    redView.backgroundColor = [UIColor redColor];
    redView.frame = CGRectMake(100, 100, 100, 100);
    [self.window.rootViewController.view addSubview:redView];
}

苹果系统建议使用下面的方法:

/*
 1.开启后台模式
 2.调用completionHandler,告诉系统你现在是否有新的数据更新
 3.userInfo添加一个字段:"content-available" : "1" : 只要添加了该字段,接受到通知都会在后台运行
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSLog(@"%@", userInfo);
    UIView *redView = [[UIView alloc] init];
    redView.backgroundColor = [UIColor redColor];
    redView.frame = CGRectMake(100, 100, 100, 100);
    [self.window.rootViewController.view addSubview:redView];

    completionHandler(UIBackgroundFetchResultNewData);
}

2>app已经关闭,需要重新开启,---基本实现方法和本地通知一样

原文地址:https://www.cnblogs.com/fendou0320/p/6527010.html