iOS开发 UIWebView使用

来源:互联网 发布:淘宝上买羊肉 编辑:程序博客网 时间:2024/06/05 03:19

在App开发过程中经常需要加载网页,iOS开发领域加载网页主要有两种方式:一是利用UIWebView,二是利用iOS8出现的WKWebView.下面主要介绍UIWebView,WKWebView将在下一篇文章中介绍

UIWebView 主要分四个方面讲解:1.加载网页;2.回调方法;3.网页加载进度条显示;4.原生与js交互

1.加载网页:UIVWebView加载本地网页代码和非本地网页

    UIWebView *webView = [[UIWebView alloc] init];    webView.delegate = self;    webView.frame = self.view.bounds;    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];    NSString *htmlCont = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];    // 获取当前应用的根目录    NSString *path = [[NSBundle mainBundle] bundlePath];    NSURL *baseURL = [NSURL fileURLWithPath:path];    [webView loadHTMLString:htmlCont baseURL:baseURL];        //加载非本地网页    NSURL *url = [[NSURL alloc] initWithString:@"https://www.baidu.com"];    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];    [webView loadRequest:request];
2.回调方法,回调方法比较简单,后面再介绍与js交互的时候在介绍

//网页开始加载时调用- (void)webViewDidStartLoad:(UIWebView *)webView {}//网页加载完成时调用,在该方法里面可以实现一些与js调用相关的代码- (void)webViewDidFinishLoad:(UIWebView *)webView {}//网页加载失败时调用,做相关提示- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {}
3.网页进度条显示,网页进度条显示对于UIWebView来说,目前微信,支付宝等做的显示都是假象,即使没有网也可以跑到80%。我们可以利用UIView直接画一个,启动一个定时器不断修改它的frame,在网页加载完成的回调方法里面将其隐掉即可,也可以使用比较流行的NJKWebViewProgress。下面介绍这个第三方webView进度条显示的具体使用

1)导入头文件

#import "NJKWebViewProgress.h"#import "NJKWebViewProgressView.h"@interface ViewController ()<UIWebViewDelegate,NJKWebViewProgressDelegate>@property (nonatomic, strong) UIWebView *webView;@property (nonatomic, strong) NJKWebViewProgress *webViewProgress;@property (nonatomic, strong) NJKWebViewProgressView *webViewProgressView;@end

2)初始化,注意在初始化的方法里面将webView的代理给了webViewProgress,此时webView加载完的相关调用将会被webViewProgress拦截,巧妙的是,webViewProgress拦截后又将这几个方法回调给了控制器,因此控制器里面仍然可以获取到网页的相关状态

    _webViewProgress = [[NJKWebViewProgress alloc] init];      _webView.delegate = _webViewProgress;      _webViewProgress.webViewProxyDelegate = self;      _webViewProgress.progressDelegate = self;            CGRect navBounds = self.navigationController.navigationBar.bounds;      CGRect barFrame = CGRectMake(0,                                   navBounds.size.height - 2,                                   navBounds.size.width,                                   2);      _webViewProgressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];      _webViewProgressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;      [_webViewProgressView setProgress:0 animated:YES];
        3)方法回调,控制器遵循NJKWebViewProgressDelagete和UIWebViewDelegate代理方法,虽然webView的代理方法给了webViewProgress,但在webViewProgress中又将方法回调给了控制器,因此控制器仍然是可以拿到web的回调方法。

#pragma NJKWebViewProgressDelegate-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress{    [self.webViewProgressView setProgress:progress animated:YES];    self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];}#pragma UIWebViewDelegate- (void) webViewDidStartLoad:(UIWebView *)webView{    NSLog(@"webViewDidStartLoad");}- (void) webViewDidFinishLoad:(UIWebView *)webView{    NSLog(@"webViewDidFinishLoad");}- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{    NSLog(@"didFailLoadWithError:%@", error);}
     4.原生与js交互,主要的操作是放在webViewdidFinishedLoad方法里面处理。

     1)原生调用js方法:原生调用js方法,可以直接执行webView自带stringByEvaluatingByJavaScriptFromeString方法,如获取网页的title

 [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
     这里面有一个坑需要注意,我之前公司做的一个项目需要从h5页面中调用一个js的方法,该方法返回需要分享的数据,但不管我怎么调用,该方法都没有数据返回,因为js调用返回数据到原生是一个异步的过程,因此你直接获取返回的数据是不行的,而WKWebView可以做到这点,因为WKWebView有一个异步回调的方法获取js返回的数据。还有一点需要注意的是这个方法一定是在window下面可获取的,也就是一个全局的方法。如果真的想利用stringByEvaluatingByJavaScriptFromeString调用js方法获取相关数据,也是有办法的,前端可以在需要调用的js方法里面将需要的数据附在url后面,js方法执行完会回调 -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)requestnavigationType:(UIWebViewNavigationType)navigationType;我们app端根据协商好的url判定,解析url获取数据。

     2)js调用原生方法:有两种办法来让js调用原生方法。其一是利用block将js端的代码与原生进行关联,比如h5页面有个按钮,按钮点击会调用alert方法。

- (void)webViewDidFinishLoad:(UIWebView *)webView{    // 以 html title 设置 导航栏 title    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];        // Undocumented access to UIWebView's JSContext    self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];        // 以 block 形式关联 JavaScript function    self.context[@"alert"] =    ^(NSString *str)    {        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"msg from js" message:str delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];        [alert show];    };}
     其二是利用-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType,在该方法里面进行拦截,根据url执行相关原生代码。比如h5页面有一个按钮,按钮点击要求原生弹到另外一个控制器。那我们可以和前端定义好url为secondVc://这种形式,

h5页面JS里面实现方法:

function commit(){     window.location.href = "secondVc://";}

当点击按钮的时候,requestString = "secondVc://";我们app端就可以根据url来判定执行相关动作了。

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{    NSString * requestString = request.URL.absoluteString;    NSLog(@"请求的地址:%@",requestString);    if ([requestString containsString:@"secondVc://"]){        //做你想要的操作        SecondVc *secondVC = [[UIViewController alloc] init];        [self.navigationController pushViewController:secondVC animated:YES];    }}












1 0
原创粉丝点击