// // NYWPViewModel.m // jiaPei // // Created by Ning.ge on 2024/7/24. // Copyright © 2024 JCZ. All rights reserved. // #import "NYWPViewModel.h" @interface NYWPViewModel () @property (nonatomic,assign) BOOL isLk; @property (nonatomic,assign) NSInteger code; @property (nonatomic,strong) NSString *ws; @end @implementation NYWPViewModel - (void)executeMethodWithName:(NSString *)methodName withParam:(NSString *)param { NSString *value = NYDDov_dict[methodName]; SEL selector = NSSelectorFromString([NSString stringWithFormat:@"%@:", value]); if ([self respondsToSelector:selector]) { [self performSelector:selector withObject:param]; } else { NSLog(@"Method not found: %@", methodName); } } - (WKWebView *)wView{ if(!_wView){ WKUserContentController *userContentController = [[WKUserContentController alloc] init]; NYUSerADD0 NYUSerADD1 NYUSerADD2 NYUSerADD3 NYUSerADD4 NSMutableString *jsString = [NSMutableString string]; [jsString appendString:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"]; [jsString appendString:@"document.documentElement.style.webkitTouchCallout='none';"]; [jsString appendString:@"document.documentElement.style.webkitUserSelect='none';"]; [jsString appendString:@"var script = document.createElement('meta');" "script.name = 'viewport';" "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";" "document.getElementsByTagName('head')[0].appendChild(script);"]; WKUserScript *userScript = [[WKUserScript alloc] initWithSource:jsString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; [userContentController addUserScript:userScript]; NSString *userAgent = @""; if (!(([[[UIDevice currentDevice] systemVersion] floatValue]) >= 9.0)) [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"userAgent":userAgent}]; WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; configuration.allowsInlineMediaPlayback = YES; if (@available(iOS 10.0, *)) { configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone; } configuration.userContentController = userContentController; WKWebView *view = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 300) configuration:configuration]; view.navigationDelegate = self; view.UIDelegate = self; if (@available(iOS 9.0, *)) { view.customUserAgent = userAgent; } else { // Fallback on earlier versions } _wView = view; } return _wView; } #pragma mark - WKNavigationDelegate - (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation { } - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation { } - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error { } - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSLog(@"navigationAction.request.URL: %@", navigationAction.request.URL); WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;//允许 NSString *urlString = [[navigationAction.request URL] absoluteString]; if([urlString containsString:self.ws]) { [MBProgressHUD rq_hideHUD]; actionPolicy =WKNavigationActionPolicyCancel;//不允许跳转 NSURL*url = [NSURL URLWithString:urlString]; if([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) { [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) { }]; }else{ [[UIApplication sharedApplication]openURL:webView.URL]; } //延迟1秒 [self performSelector:@selector(showUpview) withObject:nil afterDelay:1.0]; } decisionHandler(actionPolicy); } - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { decisionHandler(WKNavigationResponsePolicyAllow); } - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler { NSURLCredential *cred = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust]; completionHandler(NSURLSessionAuthChallengeUseCredential, cred); } #pragma mark - WKScriptMessageHandler - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ [MBProgressHUD rq_hideHUD]; if(self.isLk){ return; } self.isLk = YES; NSString *vt = (NSString *)message.body; [self executeMethodWithName:message.name withParam:vt]; self.isLk = NO; } #pragma mark - WKUIDelegate - (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures { /// CoderMike Fixed : 解决点击网页的链接 不跳转的Bug。 WKFrameInfo *frameInfo = navigationAction.targetFrame; if (![frameInfo isMainFrame]) { [webView loadRequest:navigationAction.request]; } return nil; } #pragma mark runJavaScript - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler { // [NSObject rq_showAlertViewWithTitle:nil message:message confirmTitle:@"我知道了"]; completionHandler(); } - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler { completionHandler(YES); } - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler { completionHandler(defaultText); } - (void)callHph:(int )sf{ NSString *Notification = @""; if(sf==1){ Notification = RQUserNotificationOrWechatSuccess; }else{ Notification = RQUserNotificationOrWechatFail; } [[NSNotificationCenter defaultCenter] postNotificationName:Notification object:nil userInfo:nil]; } - (void)callApa:(NSString *)ap{ [MBProgressHUD rq_showProgressHUD:@"购买中..."]; NSString *idStr = [NSString stringWithFormat:@"com.kestrel.JSJPStudent.vip.%ld",self.code]; [[IAPManager shareIAPManager] startPurchaseWithID:idStr completeHandle:^(IAPPurchType type, NSData * _Nonnull data, NSString * _Nonnull transactionIdentifier, BOOL isTest) { if (type == IAPPurchSuccess) { [[RQ_HTTP_Service postApplePayWithReceiptData:data transactionIdentifier:transactionIdentifier type:YES] subscribeNext:^(id _Nullable x) { [MBProgressHUD rq_hideHUD]; [[NSNotificationCenter defaultCenter] postNotificationName:RQUserNotificationOrWechatSuccess object:nil userInfo:nil]; } error:^(NSError * _Nullable error) { [MBProgressHUD rq_hideHUD]; [MBProgressHUD rq_showErrorTips:error]; }]; } else { [MBProgressHUD rq_hideHUD]; } }]; } - (void)callSsd:(NSString *)ttl{ [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ttl]]; } - (void)showUpview { [RQ_SHARE_FUNCTION showAlertWithTitle:@"提示" message:@"刷新信息" alertControllerStyle:UIAlertControllerStyleAlert cancelButtonTitle:@"失败" otherButtonTitles:@[@"成功"] otherButtonStyles:nil showInWindow:NO completion:^(NSUInteger selectedOtherButtonIndex) { if (selectedOtherButtonIndex == 0) { [self callHph:1]; }else{ [self callHph:0]; } }]; } - (void)callRee:(NSString *)pur{ NSLog(@"错误码:%@",pur); ShowMsg([NSString stringWithFormat:@"服务器发生了%@错误",pur]); } - (void)callLad:(NSString *)ad{ self.ws = ad; } - (NSDictionary *)getPudict{ NSDictionary *obj = @{ @"id":RQ_USER_MANAGER.currentUser._id, @"loginCode":RQ_USER_MANAGER.currentUser.loginCode==nil?@"":RQ_USER_MANAGER.currentUser.loginCode, @"nickName":RQ_USER_MANAGER.currentUser.nickName, @"pxkm":RQ_USER_MANAGER.currentUser.pxkm==nil?@"":RQ_USER_MANAGER.currentUser.pxkm, @"apsw":RQ_COMMON_MANAGER.APP_SWITCH?@"1":@"0", @"apt":[NSString stringWithFormat:@"%zd",RQ_COMMON_MANAGER.JSJP_iOS_PT] }; return obj; } -(void)wkvPL:(NSString *)httpUrl{ /// 加载请求数据 NSString *encodedString = (NSString*) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)httpUrl,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL, kCFStringEncodingUTF8)); NSURL *url = [NSURL URLWithString:encodedString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [self.wView loadRequest:request]; } -(void)wwvPLJS:(NSInteger)code{ self.code = code; [MBProgressHUD rq_showProgressHUD:@""]; NSDictionary *obj = [self getPudict]; [self.wView evaluateJavaScript:NYUCOdw_GO completionHandler:^(id result, NSError *error) { NSLog(@"is ++++ %@ %@", result,error); }]; } @end