? ? ? ? iOS8 以后,蘋果推出了一個(gè)新的加載網(wǎng)頁(yè)顯示的框架WebKit,它解決了在UIWebView上加載速度緩慢,占用內(nèi)存大,優(yōu)化困難等問(wèn)題,在性能和穩(wěn)定性上有了很大的提升,本文主要介紹WkWebView如何加載網(wǎng)頁(yè),并處理當(dāng)html頁(yè)面超鏈接里含有_blank時(shí)如何調(diào)用Safari瀏覽器打開該地址。
1.首先導(dǎo)入頭文件?
#import<WebKit/WebKit.h>
2.初始化及顯示
#define kScreenWidth? [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
@property (nonatomic, strong)WKWebView *webView;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kScreenHeight - 20)];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.163.com"]];
[self.webView loadRequest:request];
self.webView.navigationDelegate = self;//該代理可以用來(lái)追蹤加載過(guò)程以及決定是否執(zhí)行跳轉(zhuǎn)。
self.webView.UIDelegate = self;
[self.view addSubview:self.webView];
3.理解 HTML <a>標(biāo)簽的target屬性
_blank -- 在新窗口中打開鏈接
_parent -- 在父窗體中打開鏈接
_self -- 在當(dāng)前窗體打開鏈接,此為默認(rèn)值
_top -- 在當(dāng)前窗體打開鏈接,并替換當(dāng)前的整個(gè)窗體(框架頁(yè))
要想在新頁(yè)面中打開超鏈接所指向的地址需要實(shí)現(xiàn) - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler 這個(gè)代理方法
//接收到響應(yīng)后,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//this URL externally. If we′re doing nothing here, WKWebView will also just do nothing. Maybe this will change in a later stage of the iOS 8 Beta
參數(shù) WKNavigationAction 中有兩個(gè)屬性:sourceFrame和targetFrame,分別代表這個(gè)action的出處和目標(biāo),類型是 WKFrameInfo 。WKFrameInfo有一個(gè) mainFrame 的屬性,標(biāo)記frame是在主frame里顯示還是新開一個(gè)frame顯示
原文鏈接:http://www.lxweimin.com/p/3a75d7348843
WKFrameInfo *frameInfo = navigationAction.targetFrame;
BOOL isMainframe =[frameInfo isMainFrame];
NSLog(@"isMainframe :%d",isMainframe);
if (!isMainframe) {//打開新頁(yè)面顯示
NSURL *url = navigationAction.request.URL;
UIApplication *app = [UIApplication sharedApplication];
if ([app canOpenURL:url]) {
[app openURL:url];
}
}
decisionHandler(WKNavigationActionPolicyAllow);
}
本文參考鏈接
http://www.lxweimin.com/p/3a75d7348843
http://www.brighttj.com/ios/ios-wkwebview-new-features-and-use.html
http://www.lxweimin.com/p/3a75d7348843