1.前期准備工作
創建你的APNs keys 或者 創建推送證書,這兩個創建一個即可實現推送。這兩個創建一個即可實現推送。這兩個創建一個即可實現推送。重要的事情說三遍,我看評論區有小伙伴誤解。
1. 創建你的APNs keys
首先來到你的開發者 Certificates, Identifiers & Profiles—>Keys—>點擊+號,如下圖
分別填寫key的name,勾選用途,點擊continue,如下圖
然后點擊confrim—> Download這里需要注意你下載好keys的.p8文件后一定要保存好,因為他只能下載一次。然后把keys的.p8交給后台用做推送。如果你是通過創建APNS keys 的形式,至此准備工作結束。
2. 證書的創建
(1.)進入蘋果Apple Developer -> Member Center -> Certificates, Identifiers & Profiles – >Identifiers - >App IDs–>Edit
如上圖所示,勾選Push Notifications,然后點擊下面的Create Certificate,分別創建測試環境與生產環境的SSL推送證書。
(2)用證書文件與私鑰合成.pem文件給后台的同學
完成第(1)步后,然后在進入蘋果Apple Developer -> Member Center -> Certificates, Identifiers & Profiles – >Certificates,找到剛才的推送證書然后下載->雙擊安裝。在鑰匙串中找到這兩個證書(production&developerment)。分別導出.p12文件(證書的p12與密鑰的p12),如下圖。
得到證書的p12與密鑰的p12后,打開命令行把p12文件轉化為.pem文件
假設我的證書的p12與密鑰的p12
分別命名為:apns-dev-cert.p12;apns-dev-key.p12
首先cd到這兩個文件的目錄下,使用下面的命令分別得到apns-dev-cert.pem; apns-dev-key.pem;
openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12
openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12
cat apns-dev-cert.pem apns-dev-key.pem > apns-dev.pem
2.實現推送
打開你的項目->capabilication打開push notifications與background Modes,勾選最后一個remote notifications。
如果是iOS10以上版本還需要引入UserNotifications.framework、UserNotificationsUI.framework這兩個framework
然后再application引入頭文件#import <UserNotifications/UserNotifications.h>
if (IOS_VERSION >= 10.0) { UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter]; [center setDelegate:self]; UNAuthorizationOptions type = UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert; [center requestAuthorizationWithOptions:type completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { DBLog(@"注冊成功"); }else{ DBLog(@"注冊失敗"); } }]; }else if (IOS_VERSION >= 8.0){ UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert; UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil]; [application registerUserNotificationSettings:settings]; }else{//ios8一下 UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert; [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes]; } // 注冊獲得device Token [application registerForRemoteNotifications];
在application里面的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {}中添加上面代碼
// 將得到的deviceToken傳給SDK - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""]; NSLog(@"deviceTokenStr:\n%@",deviceTokenStr); }
// 注冊deviceToken失敗 - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{ NSLog(@"error -- %@",error); }
在application里面的添加上面兩個方法。然后再獲取設備token成功的方法里面,我們需要把獲取到的設備的token發送給后台,然后后台拿token去推送。
(3)處理推送過來的消息
1.iOS10以上版本的處理
//在前台 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{ // 需要執行這個方法,選擇是否提醒用戶,有Badge、Sound、Alert三種類型可以設置 completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); }
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{ //處理推送過來的數據 [self handlePushMessage:response.notification.request.content.userInfo]; completionHandler(); }
這個方法是在用戶點擊了消息欄的通知,進入app后會來到這里。我們可以業務邏輯。比如跳轉到相應的頁面等。
2.iOS10以下的處理
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary * _Nonnull)userInfo fetchCompletionHandler:(void (^ _Nonnull)(UIBackgroundFetchResult))completionHandler{ NSLog(@"didReceiveRemoteNotification:%@",userInfo); /* UIApplicationStateActive 應用程序處於前台 UIApplicationStateBackground 應用程序在后台,用戶從通知中心點擊消息將程序從后台調至前台 UIApplicationStateInactive 用用程序處於關閉狀態(不在前台也不在后台),用戶通過點擊通知中心的消息將客戶端從關閉狀態調至前台 */ //應用程序在前台給一個提示特別消息 if (application.applicationState == UIApplicationStateActive) { //應用程序在前台 [self createAlertViewControllerWithPushDict:userInfo]; }else{ //其他兩種情況,一種在后台程序沒有被殺死,另一種是在程序已經殺死。用戶點擊推送的消息進入app的情況處理。 [self handlePushMessage:userInfo]; } completionHandler(UIBackgroundFetchResultNewData); }
3.測試推送是否成功
到這里我們完成了基本的推送功能,但是是否能夠成功還不知道?我們可以測試一下。https://github.com/shaojiankui/SmartPush大家從github下載下來,直接運行。
1.把你的證書路徑、token以及要推送的消息放到指定的地方。
2.點擊連接服務器,這個時候會有訪問鑰匙串的請求,允許訪問鑰匙串。
3.點擊發送。