Objective-C:
1、在項目 target 中,打開Capabilitie —> Push Notifications屯吊,并會自動在項目中生成 .entitlement 文件逢倍。(很多同學(xué)升級后,獲取不到 deviceToken竿刁,大概率是由于沒開這個選項)Capabilitie —> Push Notifications自動生成 .entitlement
2黄锤、確保添加了 UserNotifications.framework,并 import到 AppDelegate食拜,記得實現(xiàn) UNUserNotificationCenterDelegate 鸵熟。
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate : UIResponder<UIApplicationDelegate,UNUserNotificationCenterDelegate>
@end
3、在 didFinishLaunchingWithOptions 方法中负甸,首先實現(xiàn) UNUserNotificationCenter delegate流强,并使用 UIUserNotificationSettings 請求權(quán)限。
//注意呻待,關(guān)于 iOS10 系統(tǒng)版本的判斷打月,可以用下面這個宏來判斷。不能再用截取字符的方法蚕捉。
#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奏篙、最后實現(xiàn)以下兩個回調(diào)。
//====================For iOS 10====================
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
NSLog(@"Userinfo %@",notification.request.content.userInfo);
//功能:可設(shè)置是否在應(yīng)用內(nèi)彈出通知
completionHandler(UNNotificationPresentationOptionAlert);
}
//點(diǎn)擊推送消息后回調(diào)
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
NSLog(@"Userinfo %@",response.notification.request.content.userInfo);
}
注意:需要根據(jù)系統(tǒng)版本號來判斷是否使用新的 UserNotifications.framework鱼冀,因此报破,不要著急刪除 iOS 10 以前的代碼悠就。
swift:
判斷iOS版本號方法:
func checkiOSVersion(version:String) -> Bool{
let iosversion : NSString = UIDevice.currentDevice().systemVersion
if (iosversion.compare(version, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedAscending) {
return true
}
return false
}