接著找一個 demo 來學習,這裡用 GitHub 上找到的範例專案:https://github.com/Turkcell/PushNotification_iOS_sdk
在程式碼中需要做以下幾件事。
這裡要適配 iOS 8:若系統回應 registerUserNotificationSettings:,就走新的 UIUserNotificationSettings 路線,否則退回舊的 registerForRemoteNotificationTypes:。
#pragma mark --------遠程通知
- (void)registerAPNSNotification {
// 適配 8.0,iOS 8 走新寫法
if (![[NSUserDefaults standardUserDefaults] boolForKey:kOatosParamsDeviceToken]) {
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
}
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self registerAPNSNotification];
// 清除所有本地通知
[application cancelAllLocalNotifications];
application.applicationIconBadgeNumber = 0;
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application {
if ([[UIApplication sharedApplication] enabledRemoteNotificationTypes] == UIRemoteNotificationTypeNone && !isLogout) {
[self registerAPNSNotification];
}
}
APNS 回傳的 deviceToken 是 NSData,實務上通常會去掉角括號與空白後轉成字串,再存起來以便日後送給後端:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [NSString stringWithFormat:@"%@", [[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""]];
DLog(@"deviceToken[%@]", token);
[[NSUserDefaults standardUserDefaults] setObject:token forKey:kOatosParamsDeviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSString *error_str = [NSString stringWithFormat:@"%@", error];
DLog(@"獲取deviceToken失敗[%@]", error_str);
}
整體流程就是:向 APNS 註冊 → 在 didRegisterForRemoteNotificationsWithDeviceToken: 中拿到 deviceToken 並上傳後端 → 後端在需要時透過 APNS 把訊息推送到這個 token。另外提醒兩點:模擬器無法接收遠程推送,必須用真機測試;而字串轉 deviceToken 時,用上面的去角括號法已足夠,但若追求嚴謹,建議直接遍歷 NSData 的位元組轉成十六進位字串。