// // WebPageViewController.m // Unity-iPhone // // Created by Hl Zhang on 2023/3/14. // #import "WebPageViewController.h" #import #include "cocos/scripting/js-bindings/manual/jsb_global.h" #include "JcWallet.h" #define SCREENWIDTH [UIScreen mainScreen].bounds.size.width #define SCREENHEIGHT [UIScreen mainScreen].bounds.size.height #import "NSDictionary+Customer.h" #import "UIViewController+Wallet.h" #import "UIViewController+QR.h" #import "UIViewController+Purchase.h" #include "cocos/scripting/js-bindings/manual/jsb_global.h" #import "GlobalData.h" #import "QRCodeReaderViewController.h" #import "QRCodeReader.h" #import "QRCodeReaderDelegate.h" #import "SimpleQRViewController.h" #import "LBXPermission.h" #import "LBXPermissionSetting.h" @interface WebPageViewController () @property (nonatomic, strong) WKWebView *webView; @end static QRCodeReaderViewController *qrcodeReaderVC = nil; static SimpleQRViewController *sqrVC = nil; @implementation WebPageViewController - (void)viewDidLoad { [super viewDidLoad]; WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; config.preferences.minimumFontSize = 10; config.preferences.javaScriptEnabled = YES; //不通过用户交互,是否可以打开窗口 config.preferences.javaScriptCanOpenWindowsAutomatically = NO; // custom user agent config.applicationNameForUserAgent = @"ios_game_web"; // [config.preferences setValue:@TRUE forKey:@"allowFileAccessFromFileURLs"]; // [config setValue:@TRUE forKey:@"allowUniversalAccessFromFileURLs"]; // Create the WKWebView self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; [self.view addSubview:self.webView]; // load from local // NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"html"]; // NSURL *baseURL = [[NSBundle mainBundle] bundleURL]; // [self.webView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL]; // NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html" subdirectory:@"html"]; // [self.webView loadFileURL:fileUrl allowingReadAccessToURL:fileUrl]; // NSURLRequest *request = [NSURLRequest requestWithURL:fileUrl]; // [self.webView loadRequest:request]; // Load the URL // NSURL *url = [NSURL URLWithString:self.url]; // NSURL *url = [NSURL URLWithString: @"http://192.168.1.16/web-wallet/index.html?t=1"]; // NSURL *url = [NSURL URLWithString: @"http://192.168.100.185/web-wallet/index.html?t=3"]; // NSURL *url = [NSURL URLWithString: @"https://test.kingsome.cn/html/wallet/web-wallet/index.html?t=3"]; // NSURL *url = [NSURL URLWithString: @"https://doc.kingsome.cn/game2006web/data/web-mobile/index.html"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [self.webView loadRequest:request]; WKUserContentController *userCC = config.userContentController; //JS调用OC 添加处理脚本 [userCC addScriptMessageHandler:self name:@"pageCall"]; NSString *gameData = [[GlobalData shareInstance] getGameData]; NSString *jSString = [NSString stringWithFormat:@"window.platform='ios_game_web'; window.gameData='%@';", gameData]; //用于进行JavaScript注入 WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; [config.userContentController addUserScript:wkUScript]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveProxyCBNotification:) name:@"ProxyCBNotification" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveCallPageNotification:) name:@"CallPageNotification" object:nil]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [self removeAllScriptMsgHandle]; } -(void)removeAllScriptMsgHandle{ WKUserContentController *controller = self.webView.configuration.userContentController; [controller removeScriptMessageHandlerForName:@"pageCall"]; } #pragma mark - WKScriptMessageHandler - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { NSLog(@"%@",NSStringFromSelector(_cmd)); NSLog(@"%@",message.body); if ([message.name isEqualToString:@"pageCall"]) { // [self showMsg: message.body]; NSDictionary *params = [NSDictionary parseJSONString:message.body]; NSString *action = params[@"action"]; NSString *funid = [NSString stringWithFormat:@"webpage_%@", params[@"funid"]]; NSDictionary *subData = params[@"data"]; if ([action isEqualToString:@"closepage"]) { [self dismissSelf:nil]; } else if ([action isEqualToString:@"scanQRCode"]) { NSString *title = params[@"title"]; [self scanQRCode:funid title:title]; } else if ([action isEqualToString:@"showQRCode"]) { NSString *title = params[@"title"]; [self showQRCode:title]; } else if ([action isEqualToString:@"authGetStoragePass"]) { UIWindow* window = [[[UIApplication sharedApplication] delegate] window]; NSString *key = params[@"key"]; [window.rootViewController authGetStoragePass:funid account:key]; } else if ([action isEqualToString:@"passStorageState"]) { UIWindow* window = [[[UIApplication sharedApplication] delegate] window]; NSString *key = params[@"key"]; [window.rootViewController passStorageState:funid account:key]; } else if ([action isEqualToString:@"storagePass"]) { UIWindow* window = [[[UIApplication sharedApplication] delegate] window]; NSString *key = params[@"key"]; NSString *pass = params[@"pass"]; [window.rootViewController storagePass:funid account:key pass:pass]; } else if ([action isEqualToString:@"proxyMethod"]) { NSString *methodNmae = params[@"methodname"]; NSArray *paramsArr = params[@"params"]; std::vector sparams; for (int i = 0; i < paramsArr.count; i++) { NSString *param = paramsArr[i]; sparams.push_back(std::string([param UTF8String], [param lengthOfBytesUsingEncoding:NSUTF8StringEncoding])); } std::string sMethdoName = std::string([methodNmae UTF8String], [methodNmae lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); std::string sfunid = std::string([funid UTF8String], [funid lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); cocos2d::nativeCallJS(sfunid, sMethdoName, sparams); } else { NSLog(@"unknown action: %@, data: %@", action, subData); } } } - (void) callPageJS:(NSString *) script { NSLog(@"call page script: %@", script); [self.webView evaluateJavaScript:script completionHandler:^(id _Nullable response, NSError * _Nullable error) { //JS 返回结果 NSLog(@"%@ %@",response,error); }]; } -(void)dismissSelf:(UIButton *)button{ [self dismissViewControllerAnimated:YES completion:nil]; } - (void)showMsg:(NSString *)msg { [[[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show]; } - (void) receiveProxyCBNotification: (NSNotification *) notification { if ([[notification name] isEqualToString:@"ProxyCBNotification"]) { NSDictionary *userInfo = notification.userInfo; NSString *funid = userInfo[@"funid"]; if ([funid hasPrefix:@"webpage_"]) { funid = [funid substringFromIndex:8]; } NSString *data = userInfo[@"data"]; NSLog (@"received ProxyCBNotification::funid: %@, data: %@", funid, data); NSString *jscode = [NSString stringWithFormat:@"proxyCallback('%@', '%@');", funid, data]; [self callPageJS: jscode]; } } - (void) receiveCallPageNotification: (NSNotification *) notification { if ([[notification name] isEqualToString:@"CallPageNotification"]) { NSDictionary *userInfo = notification.userInfo; NSString *funid = userInfo[@"funid"]; if ([funid hasPrefix:@"webpage_"]) { funid = [funid substringFromIndex:8]; } NSString *data = userInfo[@"data"]; NSLog (@"received CallPageNotification::funid: %@, data: %@", funid, data); NSString *jscode = [NSString stringWithFormat:@"nativeCall('%@', '%@');", funid, data]; [self callPageJS: jscode]; } } #pragma mark -- qrcode -(void)showQRCode:(NSString *)content { if (qrcodeReaderVC == nil) { sqrVC = [SimpleQRViewController new]; } sqrVC.content = content; // next three code set transparent for simple qr view self.definesPresentationContext = YES; sqrVC.modalPresentationStyle = UIModalPresentationOverCurrentContext; sqrVC.view.backgroundColor = [UIColor colorWithRed: 0.0/255.0 green: 0.0/255.0 blue: 0.0/255.0 alpha: 100.0/255.0]; [self presentViewController:sqrVC animated:YES completion:nil]; } -(void)beginScanQRCode:(NSString *)funid title:(NSString *) title{ std::string sfunid = std::string([funid UTF8String], [funid lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); // __weak __typeof(self) weakSelf = self; if ([QRCodeReader supportsMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]]) { // static dispatch_once_t onceToken; dispatch_async(dispatch_get_main_queue(), ^{ // if we are active again, we don't need to do this anymore if (qrcodeReaderVC == nil) { QRCodeReader *reader = [QRCodeReader readerWithMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]]; qrcodeReaderVC = [QRCodeReaderViewController readerWithCancelButtonTitle:@"Cancel" codeReader:reader startScanningAtLoad:YES showSwitchCameraButton:YES showTorchButton:YES]; qrcodeReaderVC.modalPresentationStyle = UIModalPresentationFormSheet; } [qrcodeReaderVC setCompletionWithBlock:^(NSString *resultAsString, NSError *error){ if (error != nil) { [self nativeCb:funid hasErr:YES dataStr: error.localizedDescription]; } else { NSLog(@"scan result: %@", resultAsString); [self nativeCb:funid hasErr:NO dataStr: resultAsString]; } }]; [self presentViewController:qrcodeReaderVC animated:YES completion:NULL]; }); } } -(void)scanQRCode:(NSString *)funid title:(NSString *) title{ NSLog(@"scanQRCode:: funId: %@ title: %@", funid, title); __weak __typeof(self) weakSelf = self; [LBXPermission authorizeWithType:LBXPermissionType_Camera completion:^(BOOL granted, BOOL firstTime) { if (granted) { [weakSelf beginScanQRCode:funid title:title]; } else if(!firstTime) { [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"Error" msg:@"The camera is need to scan QR codes" cancel:@"Cancel" setting:@"Setting" completion:^{ [weakSelf nativeCb:funid hasErr:YES dataStr: @"no permission, need resend"]; }]; } }]; } @end