可以先參考這篇 蘋果消息推送服務教程:第三部分 講得很清楚。
註冊推播通知
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
}
檢查使用者推播設定
// 檢查使用者推播設定
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types & UIRemoteNotificationTypeAlert) {
NSLog(@"Notification Enabled");
// 可以把token傳到server,之後server就可以靠它送推播給使用者了
[[HVPApiManager sharedManager] apiPushServiceWithToken:strDevToken withEnable:YES];
}
else {
NSLog(@"Notification not enabled");
[[HVPApiManager sharedManager] apiPushServiceWithToken:strDevToken withEnable:NO];
}
輸出註冊錯誤原因
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(@"Failed to register for remote notifications:%@", error);
}
常見的錯誤有:
Error Domain=NSCocoaErrorDomain Code=3000 "no valid 'aps-environment' entitlement string found for application"
可以先確認 Provisioning Profile 是否正確,device 是否已經註冊,另外 push notifications 只能在實機上測試。
手動開啟關閉推播
// enable
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
// disable
[[UIApplication sharedApplication] unregisterForRemoteNotifications];
接收通知
送出來的訊息格式
{
"aps":
{
"alert": "message(推播訊息)",
"badge": 1,
"sound": "default"
},
"type": "1",
"title": "title",
"id": "234"
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
for (id key in userInfo)
{
NSLog(@"KEY=%@, VALUE=%@", key, [userInfo objectForKey:key]);
}
}