最近在項目中使用推送服務,這裡把遇到的問題與解法整理出來,分享給需要的朋友。以下以百度推送為例,走一遍完整的整合流程。
打開「鑰匙串訪問」→「從證書頒發機構請求證書」→ 填寫用戶郵件地址與常用名 → 儲存 → 繼續 → 保存。完成後桌面會產生 CertificateSigningRequest.certSigningRequest(即 CSR 文件),同時鑰匙串訪問中會生成一對密鑰。
依序建立 Identifiers → Certificates → Provisioning Profiles。注意:
1. 建立 Identifiers 時,一定要勾選 Push Notifications。
2. 保證 Identifiers 中的 ID、Certificates 中的 Name、Provisioning Profiles 中的 App ID,以及應用程序中的 Bundle Identifier 保持一致。
在鑰匙串訪問 →「我的證書」中找到剛生成的 .p12 文件,導出到桌面。然後打開終端執行:
openssl pkcs12 -in push.p12 -out push.pem -nodes
即可將 .p12 文件轉換為 .pem 文件。
將 libBPush.a 和 BPush.h 添加到自己的工程下,添加時注意勾選當前 Target。
在工程中建立一個新的 Property List 文件,命名為 BPushConfig.plist,添加以下鍵值:
{
"PRODUCTION_MODE" = NO
"API_KEY" = "uZbmgZKhfumvGYGowcjSPFc1"
"DEBUG" = NO
}
PRODUCTION_MODE:必選,應用發布模式。開發證書簽名時設為 "NO";發布證書簽名時設為 "YES"。請在調試與發布時正確設置,以免推送無法到達。
API_KEY:必選,百度開發者中心為每個 app 自動分配的 api key,可在 app 基本信息中查看。
需要在工程中添加:Foundation.framework、CoreTelephony.framework、libz.dylib、SystemConfiguration.framework。
在 AppDelegate 的 application:didFinishLaunchingWithOptions: 中調用 API。由於 iOS 8 對推送有改動,需判斷設備版本:
[BPush setupChannel:launchOptions];
[BPush setDelegate:self]; // 參數對象必須實現 onMethod:response: 方法
#if SUPPORT_IOS8
// 8.0 以後使用這種方法註冊推送通知
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
UIUserNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else
#endif
{
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
}
在 application:didRegisterForRemoteNotificationsWithDeviceToken: 中調用 API:
[BPush registerDeviceToken:deviceToken]; // 必須 [BPush bindChannel]; // 必須。只有在該方法綁定成功後,app 才能接收到 Push 消息
必須實現 onMethod:response: 方法,處理綁定結果:
if ([BPushRequestMethod_Bind isEqualToString:method]) {
NSDictionary *res = [[NSDictionary alloc] initWithDictionary:data];
NSString *appid = [res valueForKey:BPushRequestAppIdKey];
NSString *userid = [res valueForKey:BPushRequestUserIdKey];
NSString *channelid = [res valueForKey:BPushRequestChannelIdKey];
int returnCode = [[res valueForKey:BPushRequestErrorCodeKey] intValue];
NSString *requestid = [res valueForKey:BPushRequestRequestIdKey];
}
在 application:didReceiveRemoteNotification: 中調用 API 處理推送回傳的數據:
[BPush handleNotification:userInfo]; // 可選
完成以上步驟,就能實現百度推送的完整整合。關鍵環節在於證書配置、環境模式的正確設置,以及 bindChannel 綁定成功——只有綁定成功,app 才能正常接收推送消息。