一、引入库
#import <WebKit/WebKit.h>
二、初始化有两种方式
// 默认初始化
- (instancetype)initWithFrame:(CGRect)frame; // 根据对webview的相关配置,进行初始化
- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
三、 加载网页与HTML代码的方式与UIWebView相同,代码如下:
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
[self.view addSubview:webView];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
WKUserContentController * con = [[WKUserContentController alloc]init];
//如果需要进行js交互,需要注册名为bky的对象。
//js调用时使用window.webkit.messageHandlers.bky.postMessage(message);调用
[con addScriptMessageHandler:self name:@"bky"];
config.userContentController = con;
_myWebView = [[WKWebView alloc] initWithFrame:self.bounds configuration:config];
_myWebView.navigationDelegate = self;
_myWebView.UIDelegate = self;
[self addSubview:_myWebView];
四、WKWebView的代理方法
1、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;
2、WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;
剩下三个代理方法全都是与界面弹出提示框相关的,针对于web界面的三种提示框(警告框、确认框、输入框)分别对应三种代理方法。
/**
* web界面中有弹出警告框时调用
*
* @param webView 实现该代理的webview
* @param message 警告框中的内容
* @param frame 主窗口
* @param completionHandler 警告框消失调用
*/
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(void (^)())completionHandler;
/**
* web界面中弹出确认框
*
* @param webView 实现该代理的webview
* @param message 确认框中的内容
* @param frame 主窗口
* @param completionHandler 确认框消失调用
*/
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
/**
* web界面中有弹出输入框时调用
*
* @param webView 实现该代理的webview
* @param prompt 提示的内容
* @param defaultText 输入框填写的内容
* @param frame 主窗口
* @param completionHandler 提示框消失调用
*/
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler;
3、WKScriptMessageHandler
js调用原生方法
// 从web界面中接收到一个脚本时调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
五、WKWebView加载JS
// 图片缩放的js代码
NSString *js = @"var count = document.images.length;for (var i = 0; i < count; i++) {var image = document.images[i];image.style.width=320;};window.alert('找到' + count + '张图');"; // 根据JS字符串初始化WKUserScript对象 WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; // 根据生成的WKUserScript对象,初始化WKWebViewConfiguration WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; [config.userContentController addUserScript:script]; _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; [_webView loadHTMLString:@"<head></head><img src='http://www.nsu.edu.cn/v/2014v3/img/background/3.jpg' />"baseURL:nil];
[self.view addSubview:_webView];
六、webview通过js获取网页的一些信息
//webview获得网页html代码
NSString *jsToGetHTMLSource = @"document.documentElement.innerHTML";
[self.myWebView evaluateJavaScript:jsToGetHTMLSource completionHandler:^(id _Nullable string, NSError * _Nullable error) {
NSLog(@"%@",string);
}];
//修改网页字体
[ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '10%'" completionHandler:nil];
[webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.font=\"40px arial\"" completionHandler:nil];
//wkwebview获得网页内图片 static NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=;i<objs.length;i++){\
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};";
[webView evaluateJavaScript:jsGetImages completionHandler:nil];
[webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@",result);
NSArray *array=[result componentsSeparatedByString:@"+"];
NSMutableArray *muArray = [array mutableCopy];
[muArray removeObject:@""];
NSLog(@"array====%@",array);
NSLog(@"muArray===%@",muArray); }];
七、进度条
[_myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{ // 首先,判断是哪个路径 if ([keyPath isEqualToString:@"estimatedProgress"])
{
if (self.myWebView.estimatedProgress == 1.0)
{ }
else
{
} } }