美文网首页
iOS开发Webview交互初学

iOS开发Webview交互初学

作者: IT民工高先生 | 来源:发表于2018-03-16 11:38 被阅读0次

    总体来说,一个开发者总会遇到需要和WebView进行交互的需求,现在我就讲简单的介绍两种iOS项目中和Webview进行交互的方法。这篇文章适合入门,至于更深层次的知识,希望大家慢慢学习。

    一、Request拦截

    这是一种通过UIWebView的代理方法,对Webview发出的Request进行拦截,通过分心Request的URL,进行不同的操作。

    先看iOS代码,这里加载了一个本地的HTML文件:

    - (void)viewDidLoad {
        [super viewDidLoad];
        NSURL *htmlURL = [[NSBundle mainBundle] URLForResource:@"index.html" withExtension:nil];
        NSURLRequest *request = [NSURLRequest requestWithURL:htmlURL];
        [self.webView loadRequest:request];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (UIWebView *)webView {
        if (!_webView) {
            _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
            _webView.delegate = self;
            [self.view addSubview:_webView];
        }
        return _webView;
    }
    

    以上代码加载了本地的HTML,记得设置代理方法。接下来实现UIWebViewDelegate的方法:

    -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        NSString *scheme = request.URL.scheme;
        // 过滤拦截请求
        if ([scheme isEqualToString:@"action"]) {
            // 通过URL.host区别要做的事情
            [self handleURL:request.URL];
        }
        return YES;
    }
    
    // 处理拦截信息
    - (void)handleURL:(NSURL *)url {
        NSLog(@"%@", url.host);
        if ([url.host isEqualToString:@"content"]) {
            // 调用JS方法
            [self.webView stringByEvaluatingJavaScriptFromString:@"setContent('反向调用JS方法')"];
        }
    }
    

    下面附上简单的HTML代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>JS-OC交互</title>
    </head>
    <body>
    
    <button value="发送Request" onclick="setRequest()"/>发起Request
    
    <script>
        function loadURL(url) {
            var iFrame;
            iFrame = document.createElement("iframe");
            iFrame.setAttribute("src", url);
            iFrame.setAttribute("style", "display:none;")
            document.body.appendChild(iFrame);
            // 释放iFrame
            iFrame.parentNode.removeChild(iFrame);
            iFrame = null;
        }
    
        function setRequest() {
            loadURL("action://content");
        }
    
        function setContent(content) {
            alert(content);
        }
    
    
    </script>
    
    </body>
    </html>
    
    

    二、JSContext交互

    使用JavaScriptCore.framework来实现交互,其中我们要使用到的是JSContext。

    - (void)viewDidLoad {
        [super viewDidLoad];
        NSURL *htmlURL = [[NSBundle mainBundle] URLForResource:@"index.html" withExtension:nil];
        NSURLRequest *request = [NSURLRequest requestWithURL:htmlURL];
        [self.webView loadRequest:request];
        
        // 获取JS环境
        self.context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        
        // sendContent是JS中要调用OC的方法名,通过[JSContext currentArguments]来获取传递过来的参数
        __weak typeof(self) weakSelf = self;
        self.context[@"sendContent"] = ^() {
            // 获取传递参数
            NSArray *objs = [JSContext currentArguments];
            NSLog(@"获取到参数%@", objs);
            // 调用方法向JS传值,setContent是JS中定义的方法
            [weakSelf.context evaluateScript:@"setContent('反向调用JS')"];
        };
        
        
        
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (UIWebView *)webView {
        if (!_webView) {
            _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
            _webView.delegate = self;
            [self.view addSubview:_webView];
        }
        return _webView;
    }
    

    HTML代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>JS-OC交互</title>
    </head>
    <body>
    
    <button value="发送Request" onclick="setRequest()"/>发起Request
    
    <script>
    
        function setRequest() {
            // OC中JSContext设置的方法名
            sendContent("正向给OC传值");
        }
    
        // OC要调用的方法
        function setContent(content) {
            alert(content);
        }
    
    
    </script>
    
    </body>
    </html>
    
    

    三、其他

    当然还有其他方法实现OC和WebView的交互,我这里只做了简单的使用概述,希望各位能够通过这篇文章做一个基础入门,然后自己去学习更多的相关知识。笔者也没有做深入的学习,所以也怕自己说错,就直说基础的东西吧。

    相关文章

      网友评论

          本文标题:iOS开发Webview交互初学

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