一、UIWebView
1. 创建
// 1.创建webview,并设置大小,
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height )];
// 2.创建请求
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
// 3.加载网页
[webView loadRequest:request];
// 4.添加到界面
[self.view addSubview:webView];
2. 一些实用函数
加载函数
- (void)loadRequest:(NSURLRequest *)request;
- (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;
UIWebView不仅可以加载HTML页面,还支持pdf、word、txt、各种图片等等的显示。下面以加载mac桌面上的png图片:/Users/coohua/Desktop/bigIcon.png为例
// 1.获取url
NSURL *url = [NSURL fileURLWithPath:@"/Users/coohua/Desktop/bigIcon.png"];
// 2.创建请求
NSURLRequest *request=[NSURLRequest requestWithURL:url];
// 3.加载请求
[self.webView loadRequest:request];
网页导航刷新有关函数
// 刷新
- (void)reload;
// 停止加载
- (void)stopLoading;
// 后退函数
- (void)goBack;
// 前进函数
- (void)goForward;
// 是否可以后退
@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
// 是否可以向前
@property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
// 是否正在加载
@property (nonatomic, readonly, getter=isLoading) BOOL loading;
3 .代理协议使用:UIWebViewDelegate
//是否允许加载网页
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *urlString = request.URL.absoluteString;
NSLog(@"url=%@",urlString);
return YES;
}
//开始加载网页
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(@"开始加载-url=%@--请求体--%@",webView.request.URL,webView.request.HTTPBody);
}
//网页加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(@"加载完成-url=%@--请求体--%@",webView.request.URL,webView.request.HTTPBody);
NSLog(@"网页标题:%@",[webView stringByEvaluatingJavaScriptFromString:@"document.title"]);
}
// 网页加载错误
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSURLRequest *request = webView.request;
NSLog(@"加载失败-url=%@--错误信息--%@",[request URL],error);
}
4.oc与js交互
主要有两方面:js执行OC代码、oc调取写好的js代码
-
oc执行js代码
NSString *scriptStr = @"showAlert('这里是oc调用js')";
[_webView stringByEvaluatingJavaScriptFromString:scriptStr];
-
js执行OC代码:
例如JS要调用getData方法:
则可以在UIWebView加载url完成后,在其代理方法中添加要调用的getData方法:
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//定义好JS要调用的方法, getData就是调用的getData方法名
context[@"getData"] = ^() {
NSArray *array = [JSContext currentArguments];
[array enumerateObjectsUsingBlock:^(JSValue *value,NSUInteger idx, BOOL *stop) {
NSLog(@"%@", value.toString);
}];
};
}
二、WKWebView 功能更强大
1.创建
先导入(#import <WebKit/WebKit.h>)
// 1.创建
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height )];
// 2.创建请求
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
// 3.加载网页
[webView loadRequest:request];
// 4.添加到界面
[self.view addSubview:webView];
2. 一些实用函数
加载函数
新增了loadFileURL函数,加载本地文件。
/// 加载函数
-(WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL
-(WKNavigation *)loadRequest:(NSURLRequest *)request;
-(WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
-(WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL;
以加载本地文件举个栗子:
//模拟器调试加载mac本地文件
- (void)loadLocalFile {
// 1.创建
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height )];
// 2.创建url userName:电脑用户名
NSURL *url = [NSURL fileURLWithPath:@"/Users/userName/Desktop/1.png"];
// 3.加载文件
[webView loadFileURL:url allowingReadAccessToURL:url];
// 最后将webView添加到界面
[self.view addSubview:webView];
}
网页导航刷新相关函数
@property (nonatomic, readonly) BOOL canGoBack;
@property (nonatomic, readonly) BOOL canGoForward;
- (WKNavigation *)goBack;
- (WKNavigation *)goForward;
- (WKNavigation *)reload;
// 增加的函数 比较网络数据是否有变化,没有变化则使用缓存,否则从新请求。
- (WKNavigation *)reloadFromOrigin;
// 增加的函数 可以跳转到某个指定历史页面
- (WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item;
- (void)stopLoading;
- 一些常用属性
- allowsBackForwardNavigationGestures:BOOL类型,是否允许左右划手势导航,默认不允许
- estimatedProgress:加载进度,取值范围0~1
- title:页面title
- .scrollView.scrollEnabled:是否允许上下滚动,默认允许
- backForwardList:WKBackForwardList类型,访问历史列表,可以通过前进后退按钮访问,或者通过goToBackForwardListItem函数跳到指定页面
3.WKWebView中的代理方法
- WKNavigationDelegate
该代理提供的方法,可以用来追踪加载过程(页面开始加载、加载完成、加载失败)、决定是否执行跳转。
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
页面跳转的代理方法有三种,分为(收到跳转与决定是否跳转两种)
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation;
// 在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
// 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
- WKUIDelegate
创建一个新的WKWebView
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;
剩下三个代理方法全都是与界面弹出提示框相关的,针对于web界面的三种提示框(警告框、确认框、输入框)分别对应三种代理方法。
// 界面弹出警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(void (^)())completionHandler;
// 界面弹出确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
// 界面弹出输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
- WKScriptMessageHandler
这个协议中包含一个必须实现的方法,这个方法是native与web端交互的关键,它可以直接将接收到的JS脚本转为OC对象。
// 从web界面中接收到一个脚本时调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
4.js交互
- oc 调用js
NSString *scriptStr = @"showAlert('这里是oc调用js')";
[webView evaluateJavaScript:scriptStr completionHandler:^(id html, NSError * error) {
if (error) {
NSLog(@"%@",error);
}
}];
- js调用OC
- 先初始化WKWebView 并得遵循<WKScriptMessageHandler>协议
_wkWebView=[[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[_wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"getData"];
[self.view addSubview:_rwWebView];
NSURL *url=[[NSBundle mainBundle]URLForResource:@"index" withExtension:@"html"];
NSMutableURLRequest *tmpRequest=[[NSMutableURLRequest alloc] initWithURL:url];
[_wkWebView loadRequest:tmpRequest];
最重要的一句话是:
[_wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"getData"];
//注册一个name为getData的js方法
<WKScriptMessageHandler>协议的回调写法:
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message{
if([message.name isEqualToString:@"getData"])
{
NSString * body = [message.body objectForKey:@"body"];
// 在这里写oc 实现协议的native方法
NSString *requestTmp = [NSString stringWithString:body];
NSLog(@"%@", requestTmp);
}
在H5中需要执行的JS代码是:
if (window.webkit.messageHandlers) {window.webkit.messageHandlers.getData.postMessage({body: "这是一个消息"});}
postMessage()里面的参数可以是:Number, String, Date, Array,
Dictionary, and null.和OC对应关系为:
JS | OC |
---|---|
Number | NSNumber |
String | NSString |
Date | NSDate |
Array | NSArray |
Dictionary | NSDictionary |
null | NSNull |
html部分如下:
<!DOCTYPE html>
<html>
<header>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="document.body.clientHeight, initial-scale=1.1, minimum-scale=1.1, maximum-scale=1.1, user-scalable=no">
<script type="text/javascript">
function showAlert(message){
alert(message);
}
function btnClick() {
if (window.webkit.messageHandlers){
window.webkit.messageHandlers.getData.postMessage({body: "这是一个消息"});
}else{
getData('123','abc','456');}
}
}
</script>
</header>
<body>
<br/>
<br/>
<button type="button" onclick="btnClick()">快点我!</button>
</body>
</html>