Files
WebApp/ShenQi/AppDelegate.m
2025-10-23 16:04:56 +08:00

313 lines
15 KiB
Objective-C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// 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 <SDWebImage.h>
#import "MacroDefine.h"
#import "MainOldViewController.h"
#import "LaunchViewController.h"
#import "NotiCenterViewController.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:[NowUserId 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);
[[FIRMessaging messaging] tokenWithCompletion:^(NSString *token, NSError *error) {
if (error) {
NSLog(@"FCM Token 生成失败:%@", error.localizedDescription);
// 常见错误:
// - "Unable to resolve host":网络问题或 Firebase 服务器连接失败
// - "Invalid project number"GoogleService-Info.plist 配置错误
} else {
NSLog(@"FCM Token%@", token);
// 验证 Token 有效性:在 Firebase 控制台用该 Token 发送测试消息
}
}];
}
}
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return UIInterfaceOrientationMaskAll;
}
// 注册推送失败的回调
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"推送注册失败:%@", error.localizedDescription);
}
- (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
{
NSLog(@"Received the push notification");
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];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NotiCenterViewController *notiCenterViewController = [[NotiCenterViewController alloc] initWithNibName:@"NotiCenterViewController" bundle:nil];
notiCenterViewController.modalPresentationStyle = UIModalPresentationFullScreen;
notiCenterViewController.pushId = pushId;
[self.window.rootViewController presentViewController:notiCenterViewController animated:NO completion:nil];
});
// 上传点击 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];
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 sd_setImageWithURL:url];
imageview.userInteractionEnabled = NO;
imageview.contentMode = UIViewContentModeScaleAspectFit;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageView:)];
[bgView addGestureRecognizer:tap];
[self.window addSubview:bgView];
[bgView addSubview:imageview];
});
}else if (type == 3 && !ISNULLSTR(jumpUrl)) {
dispatch_async(dispatch_get_main_queue(), ^{
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
MainOldViewController *view = [sb instantiateViewControllerWithIdentifier:@"MainOldViewController"];
view.isPresent = YES;
view.gameURLString = jumpUrl;
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