iOS10註冊推送的細節

江楓夜雨發表於2017-01-10

iOS10註冊推送,相容低版本

1,註冊

- (void)startAuthority{
    if (iOSVersionGreaterThanOrEqualTo(@"10")) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
                NSLog(@"succeeded!");
            }
        }];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }else{
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
}

2、接收訊息

iOS10, iOS10+
收到遠端推送使用這個方法接收通知

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{

    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //應用處於後臺時的遠端推送接受


    }else{
        //應用處於前臺時的本地推送接受
    }
}

iOS10-

iOS10以下使用這個方法

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

}

注:如果兩個接收通知的方法都同時實現了,那麼iOS10的方法將不再執行】

另外,有些第三方的推送已經整合了註冊程式碼,比如友盟推送,只需要呼叫
[UMessage registerForRemoteNotifications];
即可。

相關文章