iOS UIWebView與WKWebView使用詳解


一、整體介紹

UIWebView自iOS2就有,WKWebView從iOS8才有,毫無疑問WKWebView將逐步取代笨重的UIWebView。通過簡單的測試即可發現UIWebView占用過多內存,且內存峰值更是誇張。WKWebView網頁加載速度也有提升,但是並不像內存那樣提升那么多。下面列舉一些其它的優勢: 

  • 更多的支持HTML5的特性
  • 官方宣稱的高達60fps的滾動刷新率以及內置手勢
  • Safari相同的JavaScript引擎
  • 將UIWebViewDelegate與UIWebView拆分成了14類與3個協議(官方文檔說明)
  • 另外用的比較多的,增加加載進度屬性:estimatedProgress

二、UIWebView使用說明

1 舉例:簡單的使用

UIWebView使用非常簡單,可以分為三步,也是最簡單的用法,顯示網頁

復制代碼
- (void)simpleExampleTest {
    // 1.創建webview,並設置大小,"20"為狀態欄高度
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
    // 2.創建請求
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
    // 3.加載網頁
    [webView loadRequest:request];
    
    // 最后將webView添加到界面
    [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

一共有四個方法

復制代碼
/// 是否允許加載網頁,也可獲取js要打開的url,通過截取此url可與js交互
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSString *urlString = [[request URL] absoluteString];
    urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
    NSLog(@"urlString=%@---urlComps=%@",urlString,urlComps);
    return YES;
}
/// 開始加載網頁
- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSURLRequest *request = webView.request;
    NSLog(@"webViewDidStartLoad-url=%@--%@",[request URL],[request HTTPBody]);
}
/// 網頁加載完成
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSURLRequest *request = webView.request;
    NSURL *url = [request URL];
    if ([url.path isEqualToString:@"/normal.html"]) {
        NSLog(@"isEqualToString");
    }
    NSLog(@"webViewDidFinishLoad-url=%@--%@",[request URL],[request HTTPBody]);
    NSLog(@"%@",[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]);
}
/// 網頁加載錯誤
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSURLRequest *request = webView.request;
    NSLog(@"didFailLoadWithError-url=%@--%@",[request URL],[request HTTPBody]);
    
}
復制代碼

4 與js交互

主要有兩方面:js執行OC代碼、oc調取寫好的js代碼 

  • js執行OC代碼:js是不能執行oc代碼的,但是可以變相的執行,js可以將要執行的操作封裝到網絡請求里面,然后oc攔截這個請求,獲取url里面的字符串解析即可,這里用到代理協議的- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType函數。
  • oc調取寫好的js代碼:這里用到UIwebview的一個方法。示例代碼一個是網頁定位,一個是獲取網頁title:
復制代碼
// 實現自動定位js代碼, htmlLocationID為定位的位置(由js開發人員給出),實現自動定位代碼,應該在網頁加載完成之后再調用
NSString *javascriptStr = [NSString stringWithFormat:@"window.location.href = '#%@'",htmlLocationID];
// webview執行代碼
[self.webView stringByEvaluatingJavaScriptFromString:javascriptStr];

// 獲取網頁的title
NSString *title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
復制代碼

 

  • 與js交互的實例

很多時候,我們要對網頁做一些編輯,比如加載一個網頁后,個別原因,我們不想顯示新聞的來源,如下圖的新聞來源“新華網”,網頁的鏈接如下:http://op.inews.qq.com/mcms/h5/default/detail?id=NEW2016103101306200&refer=100000050(可能已經失效)

http://7xs4tc.com1.z0.glb.clouddn.com/webpage_label.png

那我們就可以使用js代碼將這個標簽去掉,且只留下時間。js代碼的編寫,根據火狐瀏覽器查看它的標簽名稱,然后做處理,如上圖,具體代碼如下:

復制代碼
- (void)deleteNewsSource {
    // 1.去掉頁面標題
    NSMutableString *str = [NSMutableString string];
    // 去掉導航頁,如果想把“騰訊新聞”導航欄一並去掉,就打開注釋
//    [str appendString:@"document.getElementsByClassName('g-header')[0].style.display = 'none';"];
    // 來源
    [str appendString:@"if(document.getElementsByClassName('g-wrapper-author')[0].innerHTML.indexOf(' ') == -1){document.getElementsByClassName('g-wrapper-author')[0].innerHTML = document.getElementsByClassName('g-wrapper-author')[0].innerHTML}else{document.getElementsByClassName('g-wrapper-author')[0].innerHTML = document.getElementsByClassName('g-wrapper-author')[0].innerHTML.split(' ')[1];}"];
    // 執行js代碼
    [_webView stringByEvaluatingJavaScriptFromString:str];
}
復制代碼

 

代碼執行的時機,一般情況下是等待網頁加載完成- (void)webViewDidFinishLoad:(UIWebView *)webView里面執行,比較合理,但是有延遲,我們會發現剛開始有來源,然后突然又沒有了,即js代碼執行有延遲。

這樣的話,我們可以在- (void)webViewDidStartLoad:(UIWebView *)webView網頁開始加載里面開啟一個定時器,比如定時0.2秒(根據需要自己設定),在定時器里面不停的調用- (void)deleteNewsSource方法即可解決。然后在- (void)webViewDidFinishLoad:(UIWebView *)webView里面關掉定時器。另外定時器容易引起循環引用,一定要注意釋放。比如可以在viewDidDisappear方法里釋放定時器。。。

- (void)webViewDidStartLoad:(UIWebView *)webView {
    // 1.去掉頁面來源標簽,時間根據需要自己設置,定時器在這里開啟具有一定危險性
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(deleteNewsSource) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    self.timer = timer;
}

 

三、WKWebView使用說明

1 簡單使用

與UIWebview一樣,僅需三步:

復制代碼
- (void)simpleExampleTest {
    // 1.創建webview,並設置大小,"20"為狀態欄高度
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
    // 2.創建請求
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
    // 3.加載網頁
    [webView loadRequest:request];
    
    // 最后將webView添加到界面
    [self.view addSubview:webView];
}
復制代碼

2 一些實用函數

  • 加載網頁函數
    相比UIWebview,WKWebView也支持各種文件格式,並新增了loadFileURL函數,顧名思義加載本地文件,不要用loadRequest來加載本地HTML,另外,加載網頁顯示屬於UI,所以應在主線程里面執行加載網頁函數,不過即使在其它線程執行了加載網頁函數,也沒關系,蘋果已做了處理,保證UI在主線程更新。
復制代碼
/// 模擬器調試加載mac本地文件
- (void)loadLocalFile {
    // 1.創建webview,並設置大小,"20"為狀態欄高度
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
    // 2.創建url  userName:電腦用戶名
    NSURL *url = [NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"];
    // 3.加載文件
    [webView loadFileURL:url allowingReadAccessToURL:url];
    // 最后將webView添加到界面
    [self.view addSubview:webView];
}

/// 其它三個加載函數
- (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;
復制代碼
  • 網頁導航刷新相關函數
    和UIWebview幾乎一樣,不同的是有返回值,WKNavigation(已更新),另外增加了函數reloadFromOrigingoToBackForwardListItem
    • reloadFromOrigin會比較網絡數據是否有變化,沒有變化則使用緩存,否則從新請求。
    • goToBackForwardListItem:比向前向后更強大,可以跳轉到某個指定歷史頁面
復制代碼
@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函數跳到指定頁面
  • 執行js代碼

/// jsStr為要執行的js代碼,字符串形式
[webView evaluateJavaScript:jsStr completionHandler:^(id item, NSError * _Nullable error) {
        // 執行結果回調
}];

3 代理協議使用

一共有三個代理協議: 

  • WKNavigationDelegate:最常用,和UIWebViewDelegate功能類似,追蹤加載過程,有是否允許加載、開始加載、加載完成、加載失敗。下面會對函數做簡單的說明,並用數字標出調用的先后次序:1-2-3-4-5

三個是否允許加載函數:

復制代碼
/// 接收到服務器跳轉請求之后調用 (服務器端redirect),不一定調用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation; 
/// 3 在收到服務器的響應頭,根據response相關信息,決定是否跳轉。decisionHandler必須調用,來決定是否跳轉,參數WKNavigationActionPolicyCancel取消跳轉,WKNavigationActionPolicyAllow允許跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
/// 1 在發送請求之前,決定是否跳轉 
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler; 
復制代碼

追蹤加載過程函數:

復制代碼
/// 2 頁面開始加載
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
/// 4 開始獲取到網頁內容時返回
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
/// 5 頁面加載完成之后調用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
/// 頁面加載失敗時調用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
復制代碼
  • WKScriptMessageHandler:必須實現的函數,是APP與js交互,提供從網頁中收消息的回調方法,即js可以調用app的方法

當然需要對webview做一些特殊處理,創建的時候調用initWithFrame:configuration:做一些配置,configurationWKWebViewConfiguration類型,具體不再詳述,代理方法如下:

/// message: 收到的腳本信息.
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
當然,app也可以執行js代碼,如下:
/// jsStr為要執行的js代碼,字符串形式
[webView evaluateJavaScript:jsStr completionHandler:^(id item, NSError * _Nullable error) {
        // 執行結果回調
}];
  • WKUIDelegate:UI界面相關,原生控件支持,三種提示框:輸入、確認、警告。首先將web提示框攔截然后再做處理。
復制代碼
/// 創建一個新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;
/// 輸入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler;
/// 確認框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
/// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
復制代碼

四、示例代碼

  • 代碼可以實現一般網絡顯示,加載本地文件(pdf、word、txt、圖片等等)
  • 搜索框搜索界面,搜索框輸入file://則加載本地文件,http://則加載網絡內容,如果兩者都不是則搜索輸入的關鍵字。
  • 下部網絡導航,后退、前進、刷新、用Safari打開鏈接四個按鈕

復制代碼
/// 控件高度
#define kSearchBarH  44
#define kBottomViewH 44

/// 屏幕大小尺寸
#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

#import "ViewController.h"
#import <WebKit/WebKit.h>


@interface ViewController () <UISearchBarDelegate, WKNavigationDelegate>

@property (nonatomic, strong) UISearchBar *searchBar;
/// 網頁控制導航欄
@property (weak, nonatomic) UIView *bottomView;

@property (nonatomic, strong) WKWebView *wkWebView;

@property (weak, nonatomic) UIButton *backBtn;
@property (weak, nonatomic) UIButton *forwardBtn;
@property (weak, nonatomic) UIButton *reloadBtn;
@property (weak, nonatomic) UIButton *browserBtn;

@property (weak, nonatomic) NSString *baseURLString;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self simpleExampleTest];
    
    [self addSubViews];
    [self refreshBottomButtonState];
    
    [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]]];
    
}
- (void)simpleExampleTest {
    // 1.創建webview,並設置大小,"20"為狀態欄高度
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
    // 2.創建請求
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]];
//    // 3.加載網頁
    [webView loadRequest:request];
//    [webView loadFileURL:[NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"] allowingReadAccessToURL:[NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"]];
    // 最后將webView添加到界面
    [self.view addSubview:webView];
}
/// 模擬器加載mac本地文件
- (void)loadLocalFile {
    // 1.創建webview,並設置大小,"20"為狀態欄高度
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
    // 2.創建url  userName:電腦用戶名
    NSURL *url = [NSURL fileURLWithPath:@"/Users/userName/Desktop/bigIcon.png"];
    // 3.加載文件
    [webView loadFileURL:url allowingReadAccessToURL:url];
    // 最后將webView添加到界面
    [self.view addSubview:webView];
}
- (void)addSubViews {
    [self addBottomViewButtons];
    
    [self.view addSubview:self.searchBar];
    
    [self.view addSubview:self.wkWebView];
}

- (void)addBottomViewButtons {
    // 記錄按鈕個數
    int count = 0;
    // 添加按鈕
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"后退" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
    button.tag = ++count;    // 標記按鈕
    [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:button];
    self.backBtn = button;
    
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"前進" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
    button.tag = ++count;
    [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:button];
    self.forwardBtn = button;
    
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"重新加載" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
    button.tag = ++count;
    [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:button];
    self.reloadBtn = button;
    
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"Safari" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
    button.tag = ++count;
    [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:button];
    self.browserBtn = button;
    // 統一設置frame
    [self setupBottomViewLayout];
}
- (void)setupBottomViewLayout
{
    int count = 4;
    CGFloat btnW = 80;
    CGFloat btnH = 30;
    
    CGFloat btnY = (self.bottomView.bounds.size.height - btnH) / 2;
    // 按鈕間間隙
    CGFloat margin = (self.bottomView.bounds.size.width - btnW * count) / count;
    
    CGFloat btnX = margin * 0.5;
    self.backBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
    
    btnX = self.backBtn.frame.origin.x + btnW + margin;
    self.forwardBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
    
    btnX = self.forwardBtn.frame.origin.x + btnW + margin;
    self.reloadBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
    
    btnX = self.reloadBtn.frame.origin.x + btnW + margin;
    self.browserBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
}
/// 刷新按鈕是否允許點擊
- (void)refreshBottomButtonState {
    if ([self.wkWebView canGoBack]) {
        self.backBtn.enabled = YES;
    } else {
        self.backBtn.enabled = NO;
    }
    
    if ([self.wkWebView canGoForward]) {
        self.forwardBtn.enabled = YES;
    } else {
        self.forwardBtn.enabled = NO;
    }
}
/// 按鈕點擊事件
- (void)onBottomButtonsClicled:(UIButton *)sender {
    switch (sender.tag) {
        case 1:
        {
            [self.wkWebView goBack];
            [self refreshBottomButtonState];
        }
            break;
        case 2:
        {
            [self.wkWebView goForward];
            [self refreshBottomButtonState];
        }
            break;
        case 3:
            [self.wkWebView reload];
            break;
        case 4:
            [[UIApplication sharedApplication] openURL:self.wkWebView.URL];
            break;
        default:
            break;
    }
}

#pragma mark - WKWebView WKNavigationDelegate 相關
/// 是否允許加載網頁 在發送請求之前,決定是否跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString *urlString = [[navigationAction.request URL] absoluteString];
    
    urlString = [urlString stringByRemovingPercentEncoding];
    //    NSLog(@"urlString=%@",urlString);
    // 用://截取字符串
    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
    if ([urlComps count]) {
        // 獲取協議頭
        NSString *protocolHead = [urlComps objectAtIndex:0];
        NSLog(@"protocolHead=%@",protocolHead);
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}


#pragma mark - searchBar代理方法
/// 點擊搜索按鈕
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    // 創建url
    NSURL *url = nil;
    NSString *urlStr = searchBar.text;
    
    // 如果file://則為打開bundle本地文件,http則為網站,否則只是一般搜索關鍵字
    if([urlStr hasPrefix:@"file://"]){
        NSRange range = [urlStr rangeOfString:@"file://"];
        NSString *fileName = [urlStr substringFromIndex:range.length];
        url = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
        // 如果是模擬器加載電腦上的文件,則用下面的代碼
//        url = [NSURL fileURLWithPath:fileName];
    }else if(urlStr.length>0){
        if ([urlStr hasPrefix:@"http://"]) {
            url=[NSURL URLWithString:urlStr];
        } else {
            urlStr=[NSString stringWithFormat:@"http://www.baidu.com/s?wd=%@",urlStr];
        }
        urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        url=[NSURL URLWithString:urlStr];
        
    }
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    
    // 加載請求頁面
    [self.wkWebView loadRequest:request];
}
#pragma mark - 懶加載
- (UIView *)bottomView {
    if (_bottomView == nil) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kBottomViewH, kScreenWidth, kBottomViewH)];
        view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
        [self.view addSubview:view];
        _bottomView = view;
    }
    return _bottomView;
}
- (UISearchBar *)searchBar {
    if (_searchBar == nil) {
        UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kSearchBarH)];
        searchBar.delegate = self;
        searchBar.text = @"http://www.cnblogs.com/mddblog/";
        _searchBar = searchBar;
        
    }
    return _searchBar;
}

- (WKWebView *)wkWebView {
    if (_wkWebView == nil) {
        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20 + kSearchBarH, kScreenWidth, kScreenHeight - 20 - kSearchBarH - kBottomViewH)];
        webView.navigationDelegate = self;
//                webView.scrollView.scrollEnabled = NO;
        
        //        webView.backgroundColor = [UIColor colorWithPatternImage:self.image];
        // 允許左右划手勢導航,默認允許
        webView.allowsBackForwardNavigationGestures = YES;
        _wkWebView = webView;
    }

    return _wkWebView;
}


@end
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM