Files
WebApp/ShenQi/AppDelegate.m
2025-01-11 09:51:47 +08:00

282 lines
13 KiB
Objective-C

//
// AppDelegate.m
// ShenQi
//
// Created by Yao on 2023/4/4.
//
#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
#import <FirebaseCore.h>
#import <FirebaseMessaging.h>
#import <Contacts/Contacts.h>
#import <AdSupport/AdSupport.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <SVProgressHUD.h>
#import "MacroDefine.h"
#import "MainOldViewController.h"
#import "LaunchViewController.h"
@interface AppDelegate () <FIRMessagingDelegate,UNUserNotificationCenterDelegate>
@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:[Tinju55UserID 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:^{}];
});
}
}
#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)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)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