美文网首页iOS学习笔记iOS学习开发
UIWebView-Objective-C 与 JavaScri

UIWebView-Objective-C 与 JavaScri

作者: FlyElephant | 来源:发表于2017-08-07 10:06 被阅读183次

如果项目中设计Html页面的,都少不了Objective-C与JavaScript的交互,如果你的项目比较新,那应该是Swift与JavaScript交互,差别不大.交互有两个形式,一种是Html页面JavaScript对方或方法调用Objective-C代码,另外一种是Objective-C调用JavaScript代码.

JavaScript 调用 Objective-C

JavaScript对方或方法调用Objective-C代码有三种方式:
1.URL拦截,通过自定义的scheme实现.
2.JavaScriptCore新增或替换JavaScript方法.
3.通过实现JSExport协议生成对象,实现JavaScript对象调用OC对象方法.

第一种方式比较常见,实现UIWebViewDelegate的可选方法:

__TVOS_PROHIBITED @protocol UIWebViewDelegate <NSObject>

@optional
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
- (void)webViewDidStartLoad:(UIWebView *)webView;
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;

@end

以访问百度网页为例:

#pragma mark - UIWebviewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSString *requestStr = [request.URL absoluteString];
    NSLog(@"网络请求地址:%@",requestStr);
    if ( [[requestStr lowercaseString] containsString:@"news"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"FlyElephant---新闻" message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *sureAlertAction = [UIAlertAction actionWithTitle:@"OK" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:sureAlertAction];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        return NO;
    }
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"开始---webViewDidStartLoad");
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"加载结束---webViewDidFinishLoad");
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"加载出错---didFailLoadWithError");
}

- (void)setUp {
    UIWebView *webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    webView.delegate = self;
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com/"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    [self.view addSubview:webView];
}
新闻.png

2.第二种方式需要一个简单的Html页面配合,代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
            <title>JavaScript页面</title>
            <script type="text/javascript">
                function jsClick2() {
                    alert('FlyElephant---本地的实现');
                }
            </script>
    </head>
    <body>
        <p>测试</p>
         <button onclick="jsClick()">测试按钮</button>
        <button onclick="jsClick2()">测试按钮2</button>
    </body>
</html>

导入JavaScriptCore头文件之后,在代理中设置JSContext.

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"加载结束---webViewDidFinishLoad");
    self.jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    [self setUpJavaScriptCallBack];
}

第一个按钮点击时候JavaScript没有对应的方法实现,第二个Objective-C对响应方法进行了重写:

    __weak typeof(self) weakSelf = self;
    self.jsContext[@"jsClick"] = ^ {
        NSArray *args = [JSContext currentArguments];
        NSMutableArray *messages = [NSMutableArray array];
        for (JSValue *obj in args) {
            [messages addObject:[obj toObject]];
        }
        [weakSelf.jsContext evaluateScript:@"alert('FlyElephant---本地的实现')"];
    };
    
    self.jsContext[@"jsClick2"] = ^ {
        [weakSelf.jsContext evaluateScript:@"alert('替换原有jsClick2方法')"];
    };
交互.png

3.JSContext并不能实现OC对象和JS对象之间的直接转换,两者面向对象的设计方式是不一样的,OC是基于类继承的,JS是基于原型的,但是所有的对象都可以视为键值对集合.

JavaScript可以脱离原型直接用JSON表示对象,但是OC不能脱离继承来表示对象,JavaScriptCore提供了JSExport作为两种语言的互通协议.

JSExport没有定义任何可选方法,需要首先定义一个实现JSExport的协议,然后在自定义协议中定义JavaScript调用方法,有点绕,看代码吧.

@protocol UserExportProtocol <JSExport>

- (void)buy:(NSString *)name;

@end


@interface User : NSObject<UserExportProtocol>

@end
@implementation User

- (void)buy:(NSString *)name {
    NSLog(@"FlyElephant买了---%@",name);
}

@end

OC端调用:

    self.jsContext[@"user"] = tempUser;
    NSString *buyStr = @"user.buy('书籍')";
    [self.jsContext evaluateScript:buyStr];

打印的Log信息如下:
FlyElephant买了---书籍
可以通过对已有的类添加JSExport协议,定义一个UIButton的扩展协议.

@protocol UIButtonExportProtocol <JSExport>

- (void)setTitle:(NSString *)title forState:(UIControlState)state;

@end
    
    self.jsContext[@"button"] = self.testButton;
    [self.jsContext evaluateScript:@"button.setTitleForState('FlyElephant 改变', 0)"];
按钮.png

Objective-C 调用 JavaScript

Objective-C调用JavaScript的方式有两种:
1.stringByEvaluatingJavaScriptFromString
2.evaluateScript

第一种方式是webView中的方法不能确定调用之后是否出错,调用的结果都是以字符串的形式方式,比较局限.

self.navigationItem.title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];

第二种方式比较简单,需要先获取JSContext:

self.jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    JSValue *value = [self.jsContext evaluateScript:@"document.title"];
    self.navigationItem.title = value.toString;
    
    [self.jsContext setExceptionHandler:^(JSContext *context, JSValue *exception){
        NSLog(@"%@", exception);
    }];

如果你觉得以上方式比较复杂,那么请选用WebViewJavascriptBridge吧,接下来会对WebViewJavascriptBridge进行源码分析,欢迎关注.

参考资料:

iOS7新JavaScriptCore框架入门介绍
JavaScriptCore框架在iOS7中的对象交互和管理

相关文章

网友评论

    本文标题:UIWebView-Objective-C 与 JavaScri

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