1. 程式人生 > >iOS 8 WkWebView 網頁的配置和前進,後退,js 互動和進度條的載入

iOS 8 WkWebView 網頁的配置和前進,後退,js 互動和進度條的載入

//  Created by 周雙建 on 15/12/21.

//  Copyright © 2015 周雙建. All rights reserved.

//

#import "ViewController.h"

//要匯入其框架

#import <WebKit/WKWebView.h>

#import <WebKit/WebKit.h>

typedefenum {

    URL_load = 0,

    HTML_load ,

    Data_load ,

    Fiel_load,

}WkwebLoadType;

@interface ViewController

()<WKNavigationDelegate,WKUIDelegate>

//建立一個實體變數

@property(nonatomic,strong) WKWebView * ZSJ_WkwebView;

// 載入type

@property(nonatomic,assign) NSInteger  IntegerType;

// 設定載入進度條

@property(nonatomic,strong) UIProgressView *  ProgressView;

@end

@implementation ViewController

- (void)viewDidLoad {

    [superviewDidLoad];

    [self makeNav];

// 建立進度條

if (!self.ProgressView) {

self.ProgressView = [[UIProgressViewalloc]initWithProgressViewStyle:UIProgressViewStyleDefault];

        self.ProgressView.frame = CGRectMake(0, 64, self.view.bounds.size.width, 1);

// 設定進度條的色彩

        [self.ProgressView

setTrackTintColor:[UIColorclearColor]];

self.ProgressView.progressTintColor = [UIColormagentaColor];

        [self.view addSubview:self.ProgressView];

    }

//初始化webview

if (!self.ZSJ_WkwebView) {

//設定網頁的配置檔案

WKWebViewConfiguration * Configuration = [[WKWebViewConfigurationalloc]init];

        //允許視訊播放

        Configuration.allowsAirPlayForMediaPlayback = YES;

// 允許線上播放

        Configuration.allowsInlineMediaPlayback = YES;

// 允許可以與網頁互動,選擇檢視

        Configuration.selectionGranularity = YES;

//建立更改資料來源

        NSString * JS = [NSString stringWithFormat:@"loadDetail(\"%d\")",70];

WKUserScript * script = [[WKUserScriptalloc] initWithSource:JS injectionTime:WKUserScriptInjectionTimeAtDocumentEndforMainFrameOnly:YES];

WKUserContentController * UserContentController = [[WKUserContentControlleralloc]init];

        [UserContentController addUserScript:script];

// 是否支援記憶讀取

        Configuration.suppressesIncrementalRendering = YES;

// 允許使用者更改網頁的設定

        Configuration.userContentController = UserContentController;

        self.ZSJ_WkwebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 66, self.view.bounds.size.width, self.view.bounds.size.height -111) configuration:Configuration];

        // 設定代理

self.ZSJ_WkwebView.navigationDelegate = self;

        self.ZSJ_WkwebView.UIDelegate = self;

// 新增進度監控

        /*

            NSKeyValueObservingOptionNew 把更改之前的值提供給處理方法

         NSKeyValueObservingOptionOld 把更改之後的值提供給處理方法

  NSKeyValueObservingOptionInitial 把初始化的值提供給處理方法,一旦註冊,立馬就會呼叫一次。通常它會帶有新值,而不會帶有舊值。

         NSKeyValueObservingOptionPrior 2次呼叫。在值改變之前和值改變之後。

         */

        [self.ZSJ_WkwebViewaddObserver:selfforKeyPath:@"estimatedProgress"options:NSKeyValueObservingOptionNewcontext:nil];

        //開啟手勢觸控

self.ZSJ_WkwebView.allowsBackForwardNavigationGestures = YES;

// 設定 可以前進 後退

//適應你設定的尺寸

        [self.ZSJ_WkwebView sizeToFit];

        //選擇載入方式

        [selfloadinteger:HTML_load];

//新增到主控制器上

        [self.view addSubview:self.ZSJ_WkwebView];

        [self makefourbtn];

    }

// Do any additional setup after loading the view, typically from a nib.

}

-(void)makeNav{

    UILabel * Nav_Label = [[UILabel alloc]initWithFrame:CGRectMake(self.view.center.x-100, 20, 200, 44)];

    Nav_Label.text = @"成功QQ吧提供";

    Nav_Label.textAlignment = NSTextAlignmentCenter;

    Nav_Label.font = [UIFont italicSystemFontOfSize:22];

    [self.view addSubview:Nav_Label];

    UIView * Line = [[UIView alloc]initWithFrame:CGRectMake(0, 63.5, self.view.bounds.size.width, 0.5)];

    Line.backgroundColor  = [UIColorlightGrayColor];

    [self.view addSubview:Line];

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    });

}

- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

-(void)makefourbtn{

    NSArray * WkWeb_Title = @[@"過載",@"後退",@"前進",@"跳轉"];

    for (int i= 0 ; i<4; i ++) {

UIButton * button = [UIButtonbuttonWithType:UIButtonTypeCustom];

        button.frame = CGRectMake(10+i*((self.view.bounds.size.width-50)/4+10), self.view.bounds.size.height - 45, (self.view.bounds.size.width-50)/4, 40);

        [button setTitle:WkWeb_Title[i] forState:UIControlStateNormal];

        button.layer.borderWidth = 0.5;

        [button setTitleColor:[UIColorblackColor] forState:UIControlStateNormal];

        button.tag = i;

        [button addTarget:selfaction:@selector(ClicK:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:button];

    }

}

-(void)ClicK:(UIButton *)Btn{

    switch (Btn.tag) {

        case 0:{

//            //這個是帶快取的驗證

//            [self.ZSJ_WkwebView reloadFromOrigin];

// 是不帶快取的驗證,重新整理當前頁面

            [self.ZSJ_WkwebView reload];

        }

            break;

        case 1:{

           // 後退

// 首先判斷網頁是否可以後退

            if (self.ZSJ_WkwebView.canGoBack) {

                [self.ZSJ_WkwebView goBack];

            }

        }

            break;

        case 2:{

            // 前進

            // 判斷是否可以前進

            if (self.ZSJ_WkwebView.canGoForward) {

                [self.ZSJ_WkwebView goForward];

            }

        }

            break;

        case 3:{

//進行跳轉,我們設定跳轉的返回到第一個介面

NSLog(@"%@",self.ZSJ_WkwebView.backForwardList.backList);

if (self.ZSJ_WkwebView.backForwardList.backList.count >2) {

                [self.ZSJ_WkwebView goToBackForwardListItem:self.ZSJ_WkwebView.backForwardList.backList[0]];

            }

        }

            break;

        default:

            break;

    }

}

-(void)loadinteger:(NSInteger)integer{

    switch (integer) {

        case 0:{

//建立一個NSURLRequest 的物件

NSURLRequest * Request_zsj = [NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gbk&word=%C3%C0%C5%AE%CD%BC%C6%AC%B4%F3%CD%BC&fr=ala&ala=1&alatpl=cover&pos=0#z=0&pn=&ic=0&st=-1&face=0&s=0&lm=-1"]];

            //載入網頁

            [self.ZSJ_WkwebView loadRequest:Request_zsj];

         }

            break;

        case 1:{

            // 獲取檔案路徑

            NSString *resourcePath = [ [NSBundle mainBundle] resourcePath];

            NSString *filePath = [resourcePath stringByAppendingPathComponent:@"test.html"];

NSString *htmlstring =[[NSStringalloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncodingerror:nil];

            [self.ZSJ_WkwebViewloadHTMLString:htmlstring baseURL:[NSURLURLWithString:[[NSBundlemainBundle] bundlePath]]];

        }

            break;

        case 2:{

        }

            break;

        case 3:{

        }

            break;

        default:

            break;

    }

}

//這個是網頁載入完成,導航的變化

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{

    /*

主意:這個方法是當網頁的內容全部顯示(網頁內的所有圖片必須都正常顯示)的時候呼叫(不是出現的時候就呼叫),,否則不顯示,或則部分顯示時這個方法就不呼叫。

     */

NSLog(@"載入完成呼叫");

// 獲取載入網頁的標題

NSLog(@"載入的標題:%@",self.ZSJ_WkwebView.title);

 }

//開始載入

-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{

//開始載入的時候,讓載入進度條顯示

self.ProgressView.hidden = NO;

NSLog(@"開始載入的時候呼叫。。");

NSLog(@"%lf",   self.ZSJ_WkwebView.estimatedProgress);

}

//內容返回時呼叫

-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{

NSLog(@"當內容返回的時候呼叫");

NSLog(@"%lf",   self.ZSJ_WkwebView.estimatedProgress);

}

-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{

NSLog(@"這是伺服器請求跳轉的時候呼叫");

}

-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{

// 內容載入失敗時候呼叫

NSLog(@"這是載入失敗時候呼叫");

    NSLog(@"%@",error);

}

-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{

NSLog(@"通過導航跳轉失敗的時候呼叫");

}

-(void)webViewDidClose:(WKWebView *)webView{

NSLog(@"網頁關閉的時候呼叫");

}

-(void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{

    NSLog(@"%lf",   webView.estimatedProgress);

}

-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{

// 獲取js 裡面的提示

}

-(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{

// js 資訊的交流

}

-(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{

// 互動。可輸入的文字。

}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

// 首先,判斷是哪個路徑

    if ([keyPath isEqualToString:@"estimatedProgress"]) {

// 判斷是哪個物件

        if (object == self.ZSJ_WkwebView) {

            NSLog(@"進度資訊:%lf",self.ZSJ_WkwebView.estimatedProgress);

            if (self.ZSJ_WkwebView.estimatedProgress == 1.0) {

                //隱藏

                self.ProgressView.hidden = YES;

            }else{

            // 新增進度數值

self.ProgressView.progress = self.ZSJ_WkwebView.estimatedProgress;

            }

        }

    }

}

//注意,觀察的移除

-(void)dealloc{

    [selfremoveObserver:selfforKeyPath:@"estimatedProgress"];

}

@end

三、效果圖。