美文网首页
【iOS开发】UIWebView

【iOS开发】UIWebView

作者: Huangbaoqin | 来源:发表于2017-10-17 02:10 被阅读122次

加载URL

_hbqWebView = [[UIWebView alloc] initWithFrame:self.view.bounds];
_hbqWebView.delegate = self;
[_hbqWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.jianshu.com/"]]];
[self.view addSubview:_hbqWebView];

不加载特定的URL

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if ([request.URL isEqual:[NSURL URLWithString:@"http://www.jianshu.com/"]]) {
        NSLog(@"no");
        return NO;
    }
    NSLog(@"yes");
    return YES;
}

UIWebViewDelegate

- (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

OC调用JavaScript

  • stringByEvaluatingJavaScriptFromString:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"finish");
    self.navigationItem.title = [_hbqWebView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
  • JavaScriptCore(iOS 7.0 +)
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //获取该UIWebView的javascript上下文
    JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //在调用前,设置异常回调
    [jsContext setExceptionHandler:^(JSContext *context, JSValue *exception){
        NSLog(@"HBQ____%@", exception);
    }];
    //这也是一种获取标题的方法。
    JSValue *value = [jsContext evaluateScript:@"document.titlexxxx"];
    //更新标题
    self.navigationItem.title = value.toString;
}

JavaScript调用OC

  • Custom URL Scheme(拦截URL)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    //标准的URL包含scheme、host、port、path、query、fragment等
    NSURL *URL = request.URL;    
    if ([URL.scheme isEqualToString:@"darkangel"]) {
        if ([URL.host isEqualToString:@"smsLogin"]) {
            NSLog(@"短信验证码登录,参数为 %@", URL.query);
            return NO;
        }
    }
    return YES;
}

·············

相关文章

网友评论

      本文标题:【iOS开发】UIWebView

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