直接切入主题,讲讲如何模拟推送以及处理推送消息。在进入主题之前,我先说几个关键流程:
1、建Push SSL Certification(推送证书)
2、OS客户端注册Push功能并获得DeviceToken
3、用Provider向APNS发送Push消息
4、OS客户端接收处理由APNS发来的消息
推送流程图:

Provider:就是为指定iOS设备应用程序提供Push的服务器。如果iOS设备的应用程序是客户端的话,那么Provider可以理解为服务端(推送消息的发起者)
APNs:Apple Push Notification Service(苹果消息推送服务器)
Devices:iOS设备,用来接收APNs下发下来的消息
Client App:iOS设备上的应用程序,用来接收APNs下发的消息到指定的一个客户端app(消息的最终响应者)
1、取Device token
App 必须要向 APNs 请求注册以实现推送功能,在请求成功后,APNs 会返回一个设备的标识符即 DeviceToken 给 App,服务器在推送通知的时候需要指定推送通知目的设备的 DeviceToken。在 iOS 8 以及之后,注册推送服务主要分为四个步骤:
- 使用 registerUserNotificationSettings:注册应用程序想要支持的推送类型
- 通过调用 registerForRemoteNotifications方法向 APNs 注册推送功能
- 请求成功时,系统会在应用程序委托方法中返回 DeviceToken,请求失败时,也会在对应的委托方法中给出请求失败的原因。
-
将 DeviceToken 上传到服务器,服务器在推送时使用。
上述第一个步骤注册的 API 是 iOS 8 新增的,因此在 iOS 7,前两个步骤需更改为 iOS 7 中的 API。
DeviceToken 有可能会更改,因此需要在程序每次启动时都去注册并且上传到你的服务器端。- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) { NSLog(@"Requesting permission for push notifications..."); // iOS 8 UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; [UIApplication.sharedApplication registerUserNotificationSettings:settings]; } else { NSLog(@"Registering device for push notifications..."); // iOS 7 and earlier [UIApplication.sharedApplication registerForRemoteNotificationTypes: UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound]; } return YES; } - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)settings { NSLog(@"Registering device for push notifications..."); // iOS 8 [application registerForRemoteNotifications]; } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token { NSLog(@"Registration successful, bundle identifier: %@, mode: %@, device token: %@", [NSBundle.mainBundle bundleIdentifier], [self modeString], token); } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSLog(@"Failed to register: %@", error); } - (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)notification completionHandler:(void(^)())completionHandler { NSLog(@"Received push notification: %@, identifier: %@", notification, identifier); // iOS 8 completionHandler(); } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification { NSLog(@"Received push notification: %@", notification); // iOS 7 and earlier } - (NSString *)modeString { #if DEBUG return @"Development (sandbox)"; #else return @"Production"; #endif }










