美文网首页
iOS UIWebView实现JS/html交互

iOS UIWebView实现JS/html交互

作者: 纵昂 | 来源:发表于2019-08-20 09:48 被阅读0次

一、导入JS头文件

#import <JavaScriptCore/JavaScriptCore.h>

二、设置代理

<UIWebViewDelegate>
#UIWebView所有的代理方法
# - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType API_DEPRECATED("No longer supported.", ios(2.0, 12.0));
# - (void)webViewDidStartLoad:(UIWebView *)webView API_DEPRECATED("No longer supported.", ios(2.0, 12.0));
# - (void)webViewDidFinishLoad:(UIWebView *)webView API_DEPRECATED("No longer supported.", ios(2.0, 12.0));
# - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error API_DEPRECATED("No longer supported.", ios(2.0, 12.0));

三、定义变量并初始化

@property (nonatomic,strong) UIWebView *webView;
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
//    NSURL *url = [NSURL URLWithString:self.url];
//    self.webView.UIDelegate = self;
//    self.webView.navigationDelegate = self;
//    NSString *body = self.body;
//    NSLog(@">>>%@",self.url);
//
////    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
////    [request setHTTPMethod: @"POST"];
////    [request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
//    _originRequest= [[NSMutableURLRequest alloc]initWithURL:url];
//    [self.webView loadRequest: _originRequest];
   
    // Do any additional setup after loading the view.
    [SVProgressHUD load];
    
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    NSURL *url = [NSURL URLWithString:self.url]; //    @"https://www.baidu.com"
    self.webView.delegate = self; //代理
    _originRequest= [[NSMutableURLRequest alloc]initWithURL:url];
    [self.webView loadRequest: _originRequest];
    [self.view addSubview:self.webView];
}

四、实现代理方法

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString],_authenticated);
    
    if(!_authenticated) {
        
        _authenticated=NO;
        
        _urlConnection= [[NSURLConnection alloc]initWithRequest:_originRequest delegate:self];
        
        [_urlConnection start];
        
        return NO;
        
    }
    
    return YES;
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    JSContext *content = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    content[@"back"] = ^() {
//        NSArray *arguments = [JSContext currentArguments];
//        for (JSValue *jsValue in arguments) {
//            NSLog(@"=======%@",jsValue);
//        }
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[AuthenticationCenterViewController class]]) {
                AuthenticationCenterViewController *A =(AuthenticationCenterViewController *)controller;
                [self.navigationController popToViewController:A animated:YES];
            }
        }
        
    };
    
    
    [SVProgressHUD dismiss];
}

-(void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error

{
    
    // 102 == WebKitErrorFrameLoadInterruptedByPolicyChange
    
    NSLog(@"***********error:%@,errorcode=%ld,errormessage:%@",error.domain,(long)error.code,error.description);
    
    if(!([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code==102)) {
        
        //当请求出错了会做什么事情
        
    }
    [SVProgressHUD dismiss];
}

#pragma mark-NURLConnectiondelegate

-(void)connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge

{
    
    NSLog(@"WebController Got auth challange via NSURLConnection");
    
    if([challenge previousFailureCount]==0)
        
    {
        
        _authenticated=YES;
        NSURLCredential*credential=[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        
        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
        
    }else{
        
        [[challenge sender]cancelAuthenticationChallenge:challenge];
        
    }
    
}

//**重点是这个方法  第一次加载会通过一个身份验证  当身份验证通过后会来到这个方法  然后重新加载https地址  然后在这里将要传递给该地址的参数写上 就ok了

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response

{
    
    NSLog(@"WebController received response via NSURLConnection");
    
    // remake a webview call now that authentication has passed ok.
    
    _authenticated=YES;
    
    //    NSString *body = [NSString stringWithFormat:@"msg=%@",self.baseStr];
    
    [_originRequest setHTTPMethod:@"POST"];
    
    [_originRequest setHTTPBody:[self.body dataUsingEncoding:NSUTF8StringEncoding]];
    
    [self.webView loadRequest:_originRequest];
    
    // Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)
    
    [_urlConnection cancel];
    
}

- (void)URLSession:(NSURLSession*)session didReceiveChallenge:(NSURLAuthenticationChallenge*)challenge completionHandler:(void(^)(NSURLSessionAuthChallengeDisposition disposition,NSURLCredential*__nullablecredential))completionHandler{
    
    NSLog(@"didReceiveChallenge");
    
    //    if([challenge.protectionSpace.host isEqualToString:@"api.lz517.me"] /*check if this is host you trust: */ ){
    
    completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
    
    //    }
    
}

// We use this method is to accept an untrusted site which unfortunately we need to do, as our PVM servers are self signed.

- (BOOL)connection:(NSURLConnection*)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace

{
    
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
    
}

从网页在跳转原界面的方法可以用

- (void)webViewDidFinishLoad:(UIWebView *)webView {

    JSContext *content = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    content[@"click_fn"] = ^() {
        
        [self.navigationController popViewControllerAnimated:YES];

    
    };
}

菜鸟一枚,多多批评!!!

相关文章

网友评论

      本文标题:iOS UIWebView实现JS/html交互

      本文链接:https://www.haomeiwen.com/subject/mqrusctx.html