1、在项目 target 中,打开Capabilitie —> Push Notifications,并会自动在项目中生成 .entitlement 文件。(很多同学升级后,获取不到 deviceToken,大概率是由于没开这个选项)

iOS实现推送功能的注意事项
Capabilitie —> Push Notifications

iOS实现推送功能的注意事项
自动生成 .entitlement

2、确保添加了 UserNotifications.framework,并 import到 AppDelegate,记得实现 UNUserNotificationCenterDelegate 

#import 

@interface AppDelegate : UIResponder 
@end

3、在 didFinishLaunchingWithOptions 方法中,首先实现 UNUserNotificationCenter delegate,并使用 UIUserNotificationSettings 请求权限。

//注意,关于 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、最后实现以下两个回调。

//====================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 以前的代码。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。