天天看點

[紹棠] iOS10實作推送功能時的注意點和問題總結

1、在項目 target 中,打開

Capabilitie —> Push Notifications

,并會自動在項目中生成 .entitlement 檔案。(很多同學更新後,擷取不到 deviceToken,大機率是由于沒開這個選項)

[紹棠] iOS10實作推送功能時的注意點和問題總結

Capabilitie —> Push Notifications

[紹棠] iOS10實作推送功能時的注意點和問題總結

自動生成 .entitlement

2、確定添加了

 UserNotifications.framework

,并 

import

到 

AppDelegate

,記得實作 

UNUserNotificationCenterDelegate 

?

1 2 3 4

#import <UserNotifications/UserNotifications.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>

@end

3、在 

didFinishLaunchingWithOptions 

方法中,首先實作 

UNUserNotificationCenter delegate

,并使用 

UIUserNotificationSettings 

請求權限。

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

//注意,關于 iOS10 系統版本的判斷,可以用下面這個宏來判斷。不能再用截取字元的方法。

#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

-(

BOOL

)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

if

(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@

"10.0"

)){

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

center.delegate = self;

[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(

BOOL

granted, NSError * _Nullable error){

if

( !error ){

[[UIApplication sharedApplication] registerForRemoteNotifications];

}

}];

}

return

YES;

}

4、最後實作以下兩個回調。

?

1 2 3 4 5 6 7 8 9 10 11 12 13

//====================For iOS 10====================

-(

void

)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(

void

(^)(UNNotificationPresentationOptions options))completionHandler{

NSLog(@

"Userinfo %@"

,notification.request.content.userInfo);

//功能:可設定是否在應用内彈出通知

completionHandler(UNNotificationPresentationOptionAlert);

}

//點選推送消息後回調

-(

void

)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(

void

(^)())completionHandler{

NSLog(@

"Userinfo %@"

,response.notification.request.content.userInfo);

}

注意:需要根據系統版本号來判斷是否使用新的 

UserNotifications.framework

,是以,不要着急删除 iOS 10 以前的代碼。