// // AppDelegate+XYPush.m // Starbuds // // Created by 翟玉磊 on 2020/6/16. // Copyright © 2020 翟玉磊. All rights reserved. // #import "AppDelegate+XYPush.h" #import // iOS 10 notification #import #import "XYWalletViewController.h" #import "XYStartAnchorApplyViewController.h" #import "XYAnchorCenterViewController.h" #import "XYSetupAnchorApplyInfoViewController.h" #import "XYAnchorApplyFailureViewController.h" #import "XYOrderCenterMainViewController.h" @interface AppDelegate () @end @implementation AppDelegate (XYPush) - (void)push_application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 初始化SDK [self initCloudPush]; // 监听推送通道打开动作 [self listenerOnChannelOpened]; // 监听推送消息到达 [self registerMessageReceive]; // 点击通知将App从关闭状态启动时,将通知打开回执上报 [CloudPushSDK sendNotificationAck:launchOptions]; // 获取离线推送内容 NSDictionary*dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]; if (dictionary) { // 不为空说明是点击离线推送进入APP的 [self handleNotification:dictionary click:YES]; } } /// 推送绑定账号 /// @param callback 回调 - (void)push_bindingAccount:(void(^)(BOOL succes))callback { [CloudPushSDK bindAccount:[XYUserInfoManager nowUser].userId withCallback:^(CloudPushCallbackResult *res) { if (res.success) { NSLog(@"推送绑定账号成功"); } else { NSLog(@"推送绑定账号失败:%@", res.error); } callback(res.success); }]; } /// 推送解绑账号 /// @param callback 回调 - (void)push_unbindAccount:(void(^)(BOOL succes))callback { [CloudPushSDK unbindAccount:^(CloudPushCallbackResult *res) { if (res.success) { NSLog(@"推送解绑账号成功"); } else { NSLog(@"推送解绑账号失败:%@", res.error); } callback(res.success); }]; } #pragma mark APNs Register /** * 向APNs注册,获取deviceToken用于推送 */ - (void)registerAPNS:(UIApplication *)application { float systemVersionNum = [[[UIDevice currentDevice] systemVersion] floatValue]; if (systemVersionNum >= 10.0) { // iOS 10 notifications UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter]; notificationCenter.delegate = self; // 请求推送权限 [notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { // granted NSLog(@"User authored notification."); // 向APNs注册,获取deviceToken dispatch_async(dispatch_get_main_queue(), ^{ [application registerForRemoteNotifications]; }); } else { // not granted NSLog(@"User denied notification."); } }]; } else if (systemVersionNum >= 8.0) { // iOS 8 Notifications #pragma clang diagnostic push #pragma clang diagnostic ignored"-Wdeprecated-declarations" [application registerUserNotificationSettings: [UIUserNotificationSettings settingsForTypes: (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]]; [application registerForRemoteNotifications]; #pragma clang diagnostic pop } else { // iOS < 8 Notifications #pragma clang diagnostic push #pragma clang diagnostic ignored"-Wdeprecated-declarations" [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)]; #pragma clang diagnostic pop } } /// 推送注册成功,返回deviceToken - (void)push_application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *res) { if (res.success) { NSLog(@"Register deviceToken success, deviceToken: %@", [CloudPushSDK getApnsDeviceToken]); // 后台注册设备 [[XYConfigAPIManager new] registerDeviceWithDeviceId:[CloudPushSDK getDeviceId] successHandler:^(ZYLResponseModel *responseModel) { } failureHandler:^(ZYLNetworkError *error) { }]; } else { NSLog(@"Register deviceToken failed, error: %@", res.error); } }]; } #pragma mark SDK Init - (void)initCloudPush { // 正式上线建议关闭 #if DEBUG [CloudPushSDK turnOnDebug]; #endif // SDK初始化,手动输出appKey和appSecret [CloudPushSDK asyncInit:self.appConfigModel.channelConfig.pushAppKey appSecret:self.appConfigModel.channelConfig.pushAppSecret callback:^(CloudPushCallbackResult *res) { if (res.success) { NSLog(@"Push SDK init success, deviceId: %@.", [CloudPushSDK getDeviceId]); } else { NSLog(@"Push SDK init failed, error: %@", res.error); } }]; // // SDK初始化,无需输入配置信息 // // 请从控制台下载AliyunEmasServices-Info.plist配置文件,并正确拖入工程 // [CloudPushSDK autoInit:^(CloudPushCallbackResult *res) { // if (res.success) { // NSLog(@"Push SDK init success, deviceId: %@.", [CloudPushSDK getDeviceId]); // } else { // NSLog(@"Push SDK init failed, error: %@", res.error); // } // }]; } #pragma mark Notification Open /* * App处于启动状态时,通知打开回调 */ - (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo { NSLog(@"Receive one notification."); // 取得APNS通知内容 NSDictionary *aps = [userInfo valueForKey:@"aps"]; // 内容 NSString *content = [aps valueForKey:@"alert"]; // badge数量 NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; // 播放声音 NSString *sound = [aps valueForKey:@"sound"]; // 取得通知自定义字段内容,例:获取key为"Extras"的内容 NSString *Extras = [userInfo valueForKey:@"Extras"]; //服务端中Extras字段,key是自己定义的 NSLog(@"content = [%@], badge = [%ld], sound = [%@], Extras = [%@]", content, (long)badge, sound, Extras); // iOS badge 清0 application.applicationIconBadgeNumber = 0; // 同步通知角标数到服务端 [self syncBadgeNum:0]; // 通知打开回执上报 [CloudPushSDK sendNotificationAck:userInfo]; [self handleNotification:userInfo click:NO]; } #pragma mark — UNUserNotificationCenterDelegate /** * App处于前台时收到通知(iOS 10+) */ - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { NSLog(@"Receive a notification in foregound."); // 处理iOS 10通知,并上报通知打开回执 [self handleiOS10Notification:notification click:NO]; // 通知不弹出 completionHandler(UNNotificationPresentationOptionNone); // 通知弹出,且带有声音、内容和角标 //completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge); } /** * 触发通知动作时回调,比如点击、删除通知和点击自定义action(iOS 10+) */ - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { NSString *userAction = response.actionIdentifier; // 点击通知打开 if ([userAction isEqualToString:UNNotificationDefaultActionIdentifier]) { NSLog(@"User opened the notification."); // 处理iOS 10通知,并上报通知打开回执 [self handleiOS10Notification:response.notification click:YES]; } // 通知dismiss,category创建时传入UNNotificationCategoryOptionCustomDismissAction才可以触发 if ([userAction isEqualToString:UNNotificationDismissActionIdentifier]) { NSLog(@"User dismissed the notification."); } completionHandler(); } /** * 处理iOS 10通知(iOS 10+) */ - (void)handleiOS10Notification:(UNNotification *)notification click:(BOOL)click { UNNotificationRequest *request = notification.request; UNNotificationContent *content = request.content; NSDictionary *userInfo = content.userInfo; // 通知时间 NSDate *noticeDate = notification.date; // 标题 NSString *title = content.title; // 副标题 NSString *subtitle = content.subtitle; // 内容 NSString *body = content.body; // 角标 int badge = [content.badge intValue]; // 取得通知自定义字段内容,例:获取key为"Extras"的内容 NSString *extras = [userInfo valueForKey:@"Extras"]; // 通知角标数清0 [UIApplication sharedApplication].applicationIconBadgeNumber = 0; // 同步角标数到服务端 [self syncBadgeNum:0]; // 通知打开回执上报 [CloudPushSDK sendNotificationAck:userInfo]; NSLog(@"Notification, date: %@, title: %@, subtitle: %@, body: %@, badge: %d, extras: %@.", noticeDate, title, subtitle, body, badge, extras); [self handleNotification:userInfo click:click]; } /// 处理所有消息 /// @param message 消息体 /// @param click 是否点击通知进来的 - (void)handleNotification:(NSDictionary *)message click:(BOOL)click { NSLog(@"推送通知消息体:%@", message); NSInteger actionType = [message[@"actionType"] integerValue]; if (!click) { // 不是点击通知进来的不需要进行跳转处理 return; } if (actionType == 101) { // 跳转h5 NSString *h5Url = message[@"h5Url"]; if (StringIsNotEmpty(h5Url)) { if (ApplicationDelegate.tabbarVC) { BaseWebViewController *controller = BaseWebViewController.new; controller.requestUrl = h5Url; [[self getCurrentController].navigationController pushViewController:controller animated:YES]; } } }else if (actionType == 201) { // 跳转本地 NSString *moduleType = message[@"moduleType"]; NSString *moduleId = message[@"moduleId"]; if (ApplicationDelegate.tabbarVC == nil) { // 没有tabbar控制器 没有主控制器 return; } if ([moduleType isEqualToString:@"liveRoom"]) { // 直播间 moduleId: 主播id if (StringIsNotEmpty(moduleId)) { [[XYLiveManger shareInstance] pushLiveRoom:moduleId extra:nil]; } }else if ([moduleType isEqualToString:@"profile"]) { // 个人主页 moduleId: 用户id if (StringIsNotEmpty(moduleId)) { XYUserMainViewController *controller = XYUserMainViewController.new; controller.targetId = moduleId; [[self getCurrentController].navigationController pushViewController:controller animated:YES]; } }else if ([moduleType isEqualToString:@"wallet"]) { // 钱包 moduleId: 用户id if (StringIsNotEmpty(moduleId)) { XYWalletViewController *controller = XYWalletViewController.new; [[self getCurrentController].navigationController pushViewController:controller animated:YES]; } }else if ([moduleType isEqualToString:@"anchor"]) { // 主播中心 moduleId: 用户id [[XYUserInfoManager new] updataUserInfoSuccess:^(BOOL isSuccess) { /// 认证状态 0:待认证 1:通过 2:未通过 -1:未提交 if ([XYUserInfoManager nowUser].applyStatus == -1) { [[self getCurrentController].navigationController pushViewController:XYStartAnchorApplyViewController.new animated:YES]; }else if ([XYUserInfoManager nowUser].applyStatus == 0) { [[self getCurrentController].navigationController pushViewController:XYSetupAnchorApplyInfoViewController.new animated:YES]; }else if ([XYUserInfoManager nowUser].applyStatus == 2) { [[self getCurrentController].navigationController pushViewController:XYAnchorApplyFailureViewController.new animated:YES]; }else if ([XYUserInfoManager nowUser].applyStatus == 1) { [[self getCurrentController].navigationController pushViewController:XYAnchorCenterViewController.new animated:YES]; } }]; } }else if (actionType == 501) { if (ApplicationDelegate.tabbarVC == nil) { // 没有tabbar控制器 没有主控制器 return; } // 跳转到技能订单中心 [[self getCurrentController].navigationController pushViewController:XYOrderCenterMainViewController.new animated:YES]; } } #pragma mark Channel Opened /** * 注册推送通道打开监听 */ - (void)listenerOnChannelOpened { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChannelOpened:) name:@"CCPDidChannelConnectedSuccess" object:nil]; } /** * 推送通道打开回调 */ - (void)onChannelOpened:(NSNotification *)notification { NSLog(@"消息通道建立成功"); } #pragma mark Receive Message /** * @brief 注册推送消息到来监听 */ - (void)registerMessageReceive { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageReceived:) name:@"CCPDidReceiveMessageNotification" object:nil]; } /** * 处理到来推送消息 */ - (void)onMessageReceived:(NSNotification *)notification { NSLog(@"Receive one message!"); CCPSysMessage *message = [notification object]; NSString *title = [[NSString alloc] initWithData:message.title encoding:NSUTF8StringEncoding]; NSString *body = [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding]; NSLog(@"Receive message title: %@, content: %@.", title, body); } /* 同步通知角标数到服务端 */ - (void)syncBadgeNum:(NSUInteger)badgeNum { [CloudPushSDK syncBadgeNum:badgeNum withCallback:^(CloudPushCallbackResult *res) { if (res.success) { NSLog(@"Sync badge num: [%lu] success.", (unsigned long)badgeNum); } else { NSLog(@"Sync badge num: [%lu] failed, error: %@", (unsigned long)badgeNum, res.error); } }]; } @end