1、基本用法:
@interface ViewController ()
{
UIWebView * _webView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
_webView = [[UIWebView alloc] init];
_webView.frame = self.view.bounds;
_webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
_webView.scalesPageToFit = YES;//这个属性设置为YES,web页面会根据屏幕大小自动伸缩
[self.view addSubview:_webView];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
[_webView loadRequest:request];
}
结果:
2015-12-07 09:44:51.524 07-uiwebview-01[919:19822] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
出错了,这是因为iOS9让所有的HTTP默认使用了HTTPS,原来的HTTP协议传输都改成TLS1.2协议进行传输。直接造成的情况就是App发请求的时候弹出网络无法连接
需要在info.plist里面添加如下:
然后再次运行程序:
2、UIWebViewDelegate
监视UIWebView的加载过程的一些状态,可以在适当的时候添加自己的处理操作。
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
//内容读入开始前被调用,返回YES内容的读入将交给UIWebView,返回NO后,UIWebView不进行读入处理。如果想在单击链接时进行独自处理则返回NO,在此方法中进行处理
NSLog(@"%s", __func__);
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
//内容读入开始后被调用
NSLog(@"%s", __func__);
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
//内容读入结束后被调用
NSLog(@"%s", __func__);
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error {
//内容读入过程中发生错误后被调用,可以被多次调用
NSLog(@"%s", __func__);
}
输出:
2015-12-07 09:59:40.195 07-uiwebview-01[1040:23731] -[ViewController webView:shouldStartLoadWithRequest:navigationType:]
2015-12-07 09:59:40.197 07-uiwebview-01[1040:23731] -[ViewController webViewDidStartLoad:]
2015-12-07 09:59:40.810 07-uiwebview-01[1040:23731] -[ViewController webViewDidFinishLoad:]
3、页面的控制
下面看代码:
//
// ViewController.m
// 07-uiwebview-01
//
#import "ViewController.h"
@interface ViewController () <UIWebViewDelegate>
{
UIWebView * _webView;
UIBarButtonItem * _reloadButton;
UIBarButtonItem * _stopButton;
UIBarButtonItem * _backButton;
UIBarButtonItem * _forwardButton;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"UIWebView";
self.navigationController.toolbarHidden = NO;
_webView = [[UIWebView alloc] init];
_webView.frame = self.view.bounds;
_webView.delegate = self;
_webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
_webView.scalesPageToFit = YES;
[self.view addSubview:_webView];
_reloadButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadAction)];
_stopButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(stopAction)];
_backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
_forwardButton = [[UIBarButtonItem alloc] initWithTitle:@"Forward" style:UIBarButtonItemStylePlain target:self action:@selector(forwardAction)];
UIBarButtonItem * flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
NSArray * toolsButton = @[_reloadButton, flexItem, _stopButton, flexItem, _backButton, flexItem, _forwardButton];
[self setToolbarItems:toolsButton animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
[_webView loadRequest:request];
[self updateControlEnabled];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void) reloadAction {
[_webView reload];
}
- (void) stopAction {
if (_webView.loading) {
[_webView stopLoading];
}
}
- (void) backAction {
if (_webView.canGoBack) {
[_webView goBack];
}
}
- (void) forwardAction {
if (_webView.canGoForward) {
[_webView goForward];
}
}
- (void) updateControlEnabled {
[UIApplication sharedApplication].networkActivityIndicatorVisible = _webView.loading;
_stopButton.enabled = _webView.loading;
_backButton.enabled = _webView.canGoBack;
_forwardButton.enabled = _webView.canGoForward;
}
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
//内容读入开始前被调用,返回YES内容的读入将交给UIWebView,返回NO后,UIWebView不进行读入处理。如果想在单击链接时进行独自处理则返回NO,在此方法中进行处理
NSLog(@"%s", __func__);
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
//内容读入开始后被调用
NSLog(@"%s", __func__);
[self updateControlEnabled];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
//内容读入结束后被调用
NSLog(@"%s", __func__);
[self updateControlEnabled];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error {
//内容读入过程中发生错误后被调用,可以被多次调用
NSLog(@"%s", __func__);
[self updateControlEnabled];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
开始:
下面随便点击一个超链接,如小说:
点击Back:
4、媒体数据的显示:
(1)显示图片:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSString * path = [[NSBundle mainBundle] pathForResource:@"dog" ofType:@"png"];
if (path != nil) {
NSData * data = [NSData dataWithContentsOfFile:path];
[_webView loadData:data MIMEType:@"image/png" textEncodingName:nil baseURL:nil];
}else {
NSLog(@"file not found");
}
}
加载网络图片:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
<pre name="code" class="objc"> NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1183223528,3058066243&fm=116&gp=0.jpg"]];
if (data != nil) {
[_webView loadData:data MIMEType:@"image/jpeg" textEncodingName:nil baseURL:nil];
}else {
NSLog(@"file not found");
}
}
(2)、显示pdf文档
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSString * path = [[NSBundle mainBundle] pathForResource:@"cocoapods" ofType:@"pdf"];
if (path != nil) {
NSData * data = [NSData dataWithContentsOfFile:path];
[_webView loadData:data MIMEType:@"application/pdf" textEncodingName:nil baseURL:nil];
}else {
NSLog(@"file not found");
}
}
在读取本地文件的时候,使用loadRequest: 方法会更加方便
首先说明一下:
代码:
NSString * path = [[NSBundle mainBundle] pathForResource:@"runtime_error.doc" ofType:nil];
NSURL * url = [NSURL fileURLWithPath:path];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
加载word文档:
5、传入HTML代码,显示页面:
NSString * str = @"<b>电话:</b><br /> 12345678901<br /> <b>网址:</b><br /> http://www.apple.com/<br />";
[_webView loadHTMLString:str baseURL:nil];
6、链接触摸的处理:
通过- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 检测链接触摸事件,navigationType参数如图:
//
// ViewController.m
// 07-uiwebview-02
#import "ViewController.h"
@interface ViewController () <UIWebViewDelegate>
{
UIWebView * _webView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.title = @"UIWebView";
self.view.backgroundColor = [UIColor whiteColor];
_webView = [[UIWebView alloc] init];
_webView.frame = self.view.bounds;
_webView.delegate = self;
_webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
_webView.scalesPageToFit = YES;
[self.view addSubview:_webView];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self loadHTMLFile:@"top.htm"];
}
- (void) loadHTMLFile:(NSString *) path {
NSArray * components = [path pathComponents];
NSString * resourceName = [components lastObject];
NSString * absolutePath = [[NSBundle mainBundle] pathForResource:resourceName ofType:nil];
if (absolutePath != nil) {
NSData * data = [NSData dataWithContentsOfFile:absolutePath];
[_webView loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8" baseURL:nil];
}else {
NSLog(@"%@ is not found", resourceName);
}
}
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"%s", __func__);
if (UIWebViewNavigationTypeLinkClicked == navigationType) {
NSString * url = [[request URL] path];
[self loadHTMLFile:url];
return false;
}
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
//内容读入开始后被调用
NSLog(@"%s", __func__);
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
//内容读入结束后被调用
NSLog(@"%s", __func__);
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error {
//内容读入过程中发生错误后被调用,可以被多次调用
NSLog(@"%s", __func__);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
top.htm:
<html>
<head>
<title>首页</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width" />
</head>
<body>
<h1>三个宝盒</h1>
<hr />
<h2>准备打开哪一个宝盒?</h2>
<ol>
<li /><a href="page1.htm">红色宝盒</a>
<li /><a href="page2.htm">银色宝盒</a>
<li /><a href="page3.htm">黑色宝盒</a>
</ol>
</body>
</html>
page1.htm:
<html>
<head>
<title>PAGE 1</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width" />
</head>
<body>
<h1>红色宝盒</h1>
<hr />
<h2>没有任何东西</h2>
<ol>
<li /><a href="top.htm">返回</a>
</ol>
</body>
</html>
7、JS的执行:
dojs.htm
<html>
<head>
<title>HTML的标题</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width" />
</head>
<body>
<h1>黑色宝盒</h1>
<hr />
<h2>有一个黑色的宝珠</h2>
<ol>
<li /><a href="top.htm">返回</a>
</ol>
<form action="document.title">
<input type="submit" value="执行JS" />
</form>
</body>
</html>
top.htm:
<html>
<head>
<title>首页</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width" />
</head>
<body>
<h1>三个宝盒</h1>
<hr />
<h2>准备打开哪一个宝盒?</h2>
<ol>
<li /><a href="page1.htm">红色宝盒</a>
<li /><a href="page1.htm">银色宝盒</a>
<li /><a href="page1.htm">黑色宝盒</a>
<li /><a href="dojs.htm">JS宝盒</a>
</ol>
</body>
</html>
代码:
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"%s", __func__);
if (UIWebViewNavigationTypeLinkClicked == navigationType) {
NSString * url = [[request URL] path];
[self loadHTMLFile:url];
return false;
}else if (UIWebViewNavigationTypeFormSubmitted == navigationType) {
NSString * url = [[request URL] path];
NSArray * components = [url pathComponents];
NSString * resultStr = [webView stringByEvaluatingJavaScriptFromString:[components lastObject]];
NSLog(@"%@", resultStr);
return false;
}
return YES;
}
输出:
2015-12-07 14:32:23.595 07-uiwebview-02[3989:106732] HTML的标题