UIWebView在ios(特别是7.x以下)开发中经常用到的控件之一,特别是近些年H5的的迅速发展,越来越多的原生态页面被替换,网页的加载也越发显得重要。网上关于UIWebView的详细介绍也非常多,在这里仅仅是个人的一些整理,备以后之需。
1.初始化工作
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
webView.backgroundColor = [UIColor whiteColor];
webView.delegate = self;
UIWebViewDelegate中:
- (void)webViewDidStartLoad:(UIWebView *)webView;//开始加载的时候执行
- (void)webViewDidFinishLoad:(UIWebView *)webView;//加载完成的时候执行
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error;//加载出错的时候执行
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
前三个方法都很好理解,第四个方法用来实现一些JS交互,后面会讲到
2.加载
网络:
NSURL *url = [NSURL URLWithString:@"http://www.jianshu.com"];//http://
NSURLRequest *webReq = [NSURLRequest requestWithURL:url];
[webView loadRequest:webReq];
需要添加请求头,服务端可以在这里取一些数据
NSURL *url = [NSURL URLWithString:webUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"1.0.0" forHTTPHeaderField:@"version"];
...
[webView loadRequest:request];
本地:
1.第一种方式loadRequest:
NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL* url = [NSURL fileURLWithPath:path];
NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
webView loadRequest:request];
2.第二种方式loadHTMLString:baseURL
NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[webView loadHTMLString:html baseURL:baseURL];
3.其他
[webView goBack];//返回
[webView goForward];//向前
[webView reload];//重新加载数据
[webView stopLoading];//停止加载数据
如果我们在iOS9下直接进行HTTP请求是会收到如下错误提示:
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
系统会告诉我们不能直接使用HTTP进行请求,需要在Info.plist新增一段用于控制ATS的配置: