標籤:
1、前期準備
在學習推送開發之前,開發人員需要兩樣東西,(1)、iPhone真機,因為模擬器不支援推送(2)、付費的開發人員帳號。
2、建立項目,選擇Single View Application模板。
3、註冊通知(Registration Notification)
(1)在AppDelegate檔案的application:didFinishLaunchingWithOptions:方法中添加“註冊推送”的代碼。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Register for Remote Notifications if (iOS8_OR_LATER) { [[UIApplication sharedApplication] registerForRemoteNotifications]; UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; } else { [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound]; }}
這樣iOS作業系統就知道該應用程式將需要處理推送訊息方面的內容。
通過上面的代碼,iOS作業系統與蘋果的APNS伺服器聯絡,並且獲得一個device token,這個device token用於區別運行該App的每一個硬體裝置。這個device token是用於你自己的伺服器給該裝置發送推送資訊,具體的實現方式就是你的伺服器將device token以及需要推送的資訊打包發送給蘋果的伺服器,然後蘋果的APNS伺服器負責將推送的內容分發到對應的裝置。
需要瞭解的是device token在每一個App上面都不一樣,並且在同一個App上面會因為時間改變而不同。所以蘋果推薦在每一次App啟動的時候將device token發送到你的伺服器後台,以確保device token是最新的。
4、判斷註冊通知失敗還是成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSLog(@"Did Register for Remote Notifications with Device Token (%@)", deviceToken);}- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSLog(@"Did Fail to Register for Remote Notifications"); NSLog(@"%@, %@", error, error.localizedDescription); }
5、收到通知訊息,進行訊息處理
如果收到了通知事件,那麼UIApplicationDelegate介面中的application:didReceiveRemoteNotification將會執行,你可以在這裡擷取推送的資訊,然後做出相應的處理。
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""]; NSLog(@"去除device token中的空格和<>字元:%@",deviceTokenStr);//僅僅是我參與的項目中這樣處理,見仁見智}
6、製作認證,使用真機進行推送訊息開發
這時候如果運行項目,那麼application:didFailToRegisterForRemoteNotificationsWithError將會執行,因為模擬器不支援推送,需要製作認證,使用真機做推送開發。
7、SSL Certificate認證製作
在蘋果的開發人員中心,建立App Id
推送的認證必須使用精確(Explicit)的App ID,而不能使用模糊(Wildcard) App ID。
如所示,
勾選上Push Notifications服務,如所示,
然後按照建立認證的流程,使用建立的App ID,因為需要較多,此處不再贅述。
原文連結:http://code.tutsplus.com/tutorials/setting-up-push-notifications-on-ios--cms-21925
iOS開發,推送訊息 steps