// // AppDelegate.m // ShenQi // // Created by Yao on 2023/4/4. // #import "AppDelegate.h" #import #import #import #import #import #import #import #import "MacroDefine.h" //#import "ViewController.h" #import "MainOldViewController.h" #import "LaunchViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleDark; [UIApplication sharedApplication].applicationIconBadgeNumber = 0; [FIRApp configure]; [FIRMessaging messaging].delegate = self; [SVProgressHUD setMaximumDismissTimeInterval:1.5]; [SVProgressHUD setMinimumDismissTimeInterval:1.5]; [SVProgressHUD setHapticsEnabled:NO]; [SVProgressHUD setDefaultMaskType:(SVProgressHUDMaskTypeBlack)]; UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error && granted) { //用户点击允许 dispatch_async(dispatch_get_main_queue(), ^{ [[UIApplication sharedApplication] registerForRemoteNotifications]; }); }else{ //用户点击不允许 } }]; // 每次活跃 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:AppUseURL]]; request.HTTPMethod = @"PUT"; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; NSDictionary *parmas = @{@"userId":[NSNumber numberWithInteger:[Candy916UserID integerValue]]}; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parmas options:NSJSONWritingPrettyPrinted error:nil]; request.HTTPBody = jsonData; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { }]; [dataTask resume]; return YES; } -(void)applicationDidBecomeActive:(UIApplication *)application { // 强制获取通讯录权限 if (self.data.contactApplyMode == 1) { CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; if (status == CNAuthorizationStatusNotDetermined) { CNContactStore *store = [[CNContactStore alloc] init]; [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError* _Nullable error) { if (granted == NO) { [self setupAlertContact]; } }]; }else if (status == CNAuthorizationStatusDenied) { [self setupAlertContact]; } } // 强制获取推送权限 if (self.data.noticeApplyMode == 1) { [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { // 没权限 if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) { [self setupNotificationStatus]; }else if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alertview = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Tips", nil) message:NSLocalizedString(@"Need to enable push permission", nil) preferredStyle:(UIAlertControllerStyleAlert)]; UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"SETTING", nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) { self.isRefresh = YES; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {}]; }]; [alertview addAction:action]; [self.window.rootViewController presentViewController:alertview animated:YES completion:^{}]; }); } }]; } if (self.forceUpdate == YES) { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alertview = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Tips", nil) message:NSLocalizedString(@"New version found", nil) preferredStyle:(UIAlertControllerStyleAlert)]; UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"Update", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) { self.isRefresh = NO; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.downloadUrl] options:@{} completionHandler:^(BOOL success) {}]; }]; [alertview addAction:action]; [self.window.rootViewController presentViewController:alertview animated:YES completion:^{}]; }); } // 强制填写邀请码 // NSUserDefaults *userfault = [NSUserDefaults standardUserDefaults]; // BOOL install = [userfault objectForKey:@"INSTALL"]; // if (install == NO) { // [self setupSendInvite]; // }else{ // if (self.isRefresh == YES) { // [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTI_INTO" object:nil]; // } // } } #pragma mark - 推送权限 -(void)setupNotificationStatus { [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { // 没权限 if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) { [self setupNotificationStatus]; }else if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alertview = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Tips", nil) message:NSLocalizedString(@"Need to enable push permission", nil) preferredStyle:(UIAlertControllerStyleAlert)]; UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"SETTING", nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) { self.isRefresh = YES; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {}]; }]; [alertview addAction:action]; [self.window.rootViewController presentViewController:alertview animated:YES completion:^{}]; }); } }]; } #pragma mark - 通讯录权限 -(void)setupAlertContact { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Tips", nil) message:NSLocalizedString(@"Contacts permission must be turned on", nil) preferredStyle:(UIAlertControllerStyleAlert)]; UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"SETTING", nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) { self.isRefresh = YES; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {}]; }]; [alertController addAction:action]; [self.window.rootViewController presentViewController:alertController animated:YES completion:^{}]; }); } /* -(void)refreshPermissionAll { [SVProgressHUD dismiss]; // 判断是否开启推送权限 [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { // 没权限 if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) { [self setupNotificationStatus]; }else if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alertview = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Tips", nil) message:NSLocalizedString(@"Need to enable push permission", nil) preferredStyle:(UIAlertControllerStyleAlert)]; UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"SETTING", nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) { self.isRefresh = YES; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {}]; }]; [alertview addAction:action]; [self.window.rootViewController presentViewController:alertview animated:YES completion:^{}]; }); } }]; // 判断是否开启通讯权限 CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]; if (status == CNAuthorizationStatusNotDetermined) { CNContactStore *store = [[CNContactStore alloc] init]; [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError* _Nullable error) { if (granted == NO) { [self setupAlertContact]; } }]; }else if (status == CNAuthorizationStatusDenied) { [self setupAlertContact]; } // 判断是否输入邀请码 NSUserDefaults *userfault = [NSUserDefaults standardUserDefaults]; BOOL install = [userfault objectForKey:@"INSTALL"]; if (install == NO) { [self setupSendInvite]; }else{ [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTI_INTO" object:nil]; } } #pragma mark - 填写邀请码 -(void)setupSendInvite { // 填写邀请码 dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *inputCodeAlertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Please enter the invitation code", nil) message:nil preferredStyle:(UIAlertControllerStyleAlert)]; [inputCodeAlertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.placeholder = NSLocalizedString(@"Please enter the invitation code", nil); }]; UIAlertAction *inputCodeAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) { UITextField *codeTextField = inputCodeAlertController.textFields.firstObject; if (!ISNULLSTR(codeTextField.text)) { NSString *advertisingId = codeTextField.text; [self setupInviteSend:advertisingId]; }else{ [self setupSendInvite]; } }]; [inputCodeAlertController addAction:inputCodeAction]; [self.window.rootViewController presentViewController:inputCodeAlertController animated:YES completion:^{}]; }); } -(void)setupInviteSend:(NSString *)advertisingId { __block NSString *uuidString = @""; if (@available(iOS 14, *)) { [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) { uuidString = [[ASIdentifierManager sharedManager] advertisingIdentifier].UUIDString; [self setupInviteSendWithUUIDString:uuidString advertisingId:advertisingId]; }]; } else { uuidString = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; [self setupInviteSendWithUUIDString:uuidString advertisingId:advertisingId]; } } -(void)setupInviteSendWithUUIDString:(NSString *)uuidString advertisingId:(NSString *)advertisingId { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:InviteSendURL]]; request.HTTPMethod = @"PUT"; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; NSDictionary *parmas = @{@"code":advertisingId,@"deviceCode":uuidString,@"userId":[NSNumber numberWithInteger:[VV88AUUserID integerValue]]}; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parmas options:NSJSONWritingPrettyPrinted error:nil]; request.HTTPBody = jsonData; [SVProgressHUD show]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { dispatch_async(dispatch_get_main_queue(), ^{ if (error == nil) { [SVProgressHUD dismiss]; NSError *error; NSMutableDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; if (error == nil) { NSInteger code = [[responseObject objectForKey:@"code"] integerValue]; if (ISNULL(error)) { if (code == 40001) { NSString *errmsg = [responseObject objectForKey:@"error"]; [SVProgressHUD showInfoWithStatus:errmsg]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSDictionary *datadic = [responseObject objectForKey:@"data"]; NSString *inviteCode = [datadic objectForKey:@"inviteCode"]; NSUserDefaults *userfault = [NSUserDefaults standardUserDefaults]; [userfault setObject:[NSNumber numberWithBool:YES] forKey:@"INSTALL"]; [userfault setObject:inviteCode forKey:@"INVITE_CODE"]; [userfault synchronize]; // 已填写邀请码 [self refreshPermissionAll]; }); }else if (code == 1) { NSUserDefaults *userfault = [NSUserDefaults standardUserDefaults]; [userfault setObject:[NSNumber numberWithBool:YES] forKey:@"INSTALL"]; [userfault setObject:advertisingId forKey:@"INVITE_CODE"]; [userfault synchronize]; // 已填写邀请码 [self refreshPermissionAll]; }else{ NSString *errmsg = [responseObject objectForKey:@"error"]; [SVProgressHUD showInfoWithStatus:errmsg]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self setupSendInvite]; }); } }else{ NSString *errmsg = [responseObject objectForKey:@"message"]; [SVProgressHUD showInfoWithStatus:errmsg]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self setupSendInvite]; }); } } else{ [SVProgressHUD showInfoWithStatus:error.localizedDescription]; [self setupSendInvite]; } } else{ [SVProgressHUD showInfoWithStatus:error.localizedDescription]; [self setupSendInvite]; } }); }]; [dataTask resume]; } */ - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { if (deviceToken != nil) { [[FIRMessaging messaging] setAPNSToken:deviceToken]; [[FIRMessaging messaging] subscribeToTopic:@"demo" completion:^(NSError * _Nullable error) { NSLog(@"Subscribed to demo topic"); }]; NSLog(@"APNSToken = %@",[FIRMessaging messaging].APNSToken); } } -(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return UIInterfaceOrientationMaskAll; } - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { NSLog(@"FCM registration token: %@", fcmToken); [[FIRMessaging messaging] tokenWithCompletion:^(NSString *token, NSError *error) { if (error != nil) { NSLog(@"Error getting FCM registration token: %@", error); } else { NSLog(@"FCM registration token: %@", token); } }]; } - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [self processWithNoti:userInfo]; } - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { [self processWithNoti:response.notification.request.content.userInfo]; } /* -(void)receiveNOTIProcessWithNoti:(NSDictionary *)userInfo { [[FIRMessaging messaging] appDidReceiveMessage:userInfo]; if (userInfo) { NSDictionary *apnsDic = [userInfo objectForKey:@"aps"]; NSDictionary *alertDic = [apnsDic objectForKey:@"alert"]; NSString *title = [alertDic objectForKey:@"body"]; NSString *content = [alertDic objectForKey:@"title"]; [self scheduleLocalNotification:userInfo title:title content:content]; } } - (void)scheduleLocalNotification:(NSDictionary *)userInfo title:(NSString *)title content:(NSString *)content { UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; UNMutableNotificationContent *notificationContent = [[UNMutableNotificationContent alloc] init]; notificationContent.title = title; notificationContent.subtitle = content; notificationContent.sound = [UNNotificationSound defaultSound]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"LOCAL_NOTI" content:notificationContent trigger:nil]; [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) { if (!error) { [self processWithNoti:userInfo]; } }]; } */ -(void)processWithNoti:(NSDictionary *)userInfo { NSString *message = [userInfo objectForKey:@"message"]; NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *messageNotiDic = nil; if (!ISNULL(jsonData)) { NSError *err; messageNotiDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err]; if (!ISNULL(messageNotiDic)) { NSInteger type = [[messageNotiDic objectForKey:@"type"] integerValue];// 1 文字 2 图片 3 链接 NSString *image = [messageNotiDic objectForKey:@"image"]; NSString *jumpUrl = [messageNotiDic objectForKey:@"jumpUrl"]; NSInteger pushId = [[messageNotiDic objectForKey:@"pushId"] longValue]; // 上传点击 pushId if (pushId > 0) { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:PushStatisticsURL]]; request.HTTPMethod = @"POST"; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; NSDictionary *parmas = @{@"pushId":[NSNumber numberWithLong:pushId]}; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parmas options:NSJSONWritingPrettyPrinted error:nil]; request.HTTPBody = jsonData; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { }]; [dataTask resume]; } if (type == 2 && !ISNULLSTR(image)) { dispatch_async(dispatch_get_main_queue(), ^{ NSURL *url = [NSURL URLWithString:image]; NSData *data = [NSData dataWithContentsOfURL:url]; UIView *bgView = [[UIView alloc] initWithFrame:self.window.bounds]; bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5]; UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20, 80, bgView.frame.size.width-40, bgView.frame.size.height-160)]; imageview.image = [UIImage imageWithData:data]; imageview.contentMode = UIViewContentModeScaleAspectFill; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageView:)]; [imageview addGestureRecognizer:tap]; [self.window addSubview:bgView]; [bgView addSubview:imageview]; }); }else if (type == 3 && !ISNULLSTR(jumpUrl)) { dispatch_async(dispatch_get_main_queue(), ^{ MainOldViewController *view = [[MainOldViewController alloc] init]; view.gameURLString = jumpUrl; view.isPresent = YES; view.modalPresentationStyle = UIModalPresentationFullScreen; [self.window.rootViewController presentViewController:view animated:YES completion:^{}]; }); } } } } -(void)tapImageView:(UITapGestureRecognizer *)tap { [tap.view removeFromSuperview]; } + (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host { return YES; } @end