您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 遠端推送入門:透過 Apple 伺服器實作通知

編輯:iOS 開發綜合

推送的運作機制與憑證申請流程本文不多贅述,這裡聚焦在程式碼層面:客戶端需要完成哪三件事。

一、向系統註冊接收遠端通知

通常放在 application:didFinishLaunchingWithOptions: 中:

[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert
                                    | UIRemoteNotificationTypeBadge
                                    | UIRemoteNotificationTypeSound];

這三個旗標分別對應「顯示提示文字」、「更新應用圖示上的數字」與「播放聲音」,可依需求任意組合。

二、取得 deviceToken

deviceToken 是推送的關鍵——Apple 的推送服務(APNs)完全依據這個值來定位裝置。它與全球每一台 Apple 裝置一一對應,因此是唯一的。

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"獲取設備的 deviceToken: %@", deviceToken);
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Failed to get token, error: %@", error);
}

實務上,deviceToken 取得後必須上傳到自己的伺服器並與使用者帳號關聯,否則伺服器無從得知要推給誰。另外要特別注意:deviceToken 會變動(例如使用者重新安裝 App、系統還原),因此每次啟動時都應該重新註冊並更新後端的紀錄,不能只存一次就好。

還有一個容易忽略的細節:deviceToken 是 NSData 型別,上傳前通常要轉成 64 字元的十六進位字串,否則後端無法正確比對。

三、處理收到的通知

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // 以警告框方式顯示推送內容
    if ([[userInfo objectForKey:@"aps"] objectForKey:@"alert"] != NULL) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"經過推送發送過來的消息"
                                                       message:[[userInfo objectForKey:@"aps"]
                                                                    objectForKey:@"alert"]
                                                      delegate:self
                                             cancelButtonTitle:@"關閉"
                                             otherButtonTitles:@"處理", nil];
        [alert show];
        [alert release];
    }
}

userInfo 中的 aps 字典是 Apple 保留的欄位,alert、badge、sound 都放在裡面。若伺服器自訂了額外欄位(例如文章 ID),會放在 aps 的旁邊,可以在這裡一併取出並據以跳轉到對應頁面。

兩個實務提醒

第一,App 在前景執行時,iOS 預設不會顯示系統的通知橫幅,而是直接把 userInfo 交給 didReceiveRemoteNotification:。若不希望使用者錯過,需要自行在應用內呈現提示。

第二,UIAlertView 在 iOS 8 之後已由 Apple 標記為不建議使用,新專案應改用 UIAlertController;同時推送註冊也應改用 requestAuthorizationWithOptions: 搭配 registerForRemoteNotifications 的新版 API。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved