1、首先讓前端的同事打一個包(index.html,static文件包含css、資源文件、js等)導入項目;
:warning: 注意:
把index.html放入項目根目錄下,command+n創建一個資源文件.bundle,資源文件里也的包含一份 index.html


下面開始代碼:
懶加載WKWebView
引入#import <WebKit/WebKit.h> #import <WebKit/WKWebView.h>
繼承 WKNavigationDelegate,WKUIDelegate,
- (WKWebView *)wkWebView{  if (!_wkWebView) {    //設置網頁的配置文件    WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc]init];    //允許視頻播放    if (@available(iOS 9.0, *)) {      Configuration.allowsAirPlayForMediaPlayback = YES;    } else {      // Fallback on earlier versions    }    // 允許在線播放    Configuration.allowsInlineMediaPlayback = YES;    // 允許可以與網頁交互,選擇視圖    Configuration.selectionGranularity = YES;    // 關于 WKWebView 無法跳轉新頁面 設置    Configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES;    // web內容處理池    Configuration.processPool = [[WKProcessPool alloc] init];    //自定義配置,一般用于 js調用oc方法(OC攔截URL中的數據做自定義操作)    WKUserContentController * UserContentController = [[WKUserContentController alloc]init];    // 添加消息處理,注意:self指代的對象需要遵守WKScriptMessageHandler協議,結束時需要移除    [UserContentController addScriptMessageHandler:self name:@"download"];//DownloadPolicy    // 是否支持記憶讀取    Configuration.suppressesIncrementalRendering = YES;    // 允許用戶更改網頁的設置    Configuration.userContentController = UserContentController;        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kIs_iPhoneX? self.view.frame.size.height-34:self.view.frame.size.height) configuration:Configuration];    _wkWebView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];    // 設置代理    _wkWebView.navigationDelegate = self;    _wkWebView.UIDelegate = self;    // 垂直滾動    [_wkWebView.scrollView setShowsVerticalScrollIndicator:NO];    _wkWebView.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, kIs_iPhoneX? self.view.frame.size.height-34:self.view.frame.size.height);    //開啟手勢觸摸    _wkWebView.allowsBackForwardNavigationGestures = YES;    // 設置 可以前進 和 后退    //適應你設定的尺寸    [_wkWebView sizeToFit];    [self.view addSubview:_wkWebView];  }  return _wkWebView;}iOS 9 以后和 iOS 8 之前 加載方法不一樣,做區分
- (void)viewDidLoad {  [super viewDidLoad];  NSFileManager *fileManager = [NSFileManager defaultManager];  NSArray *array1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  NSString *matPath1 = [[array1 objectAtIndex:0] stringByAppendingPathComponent:@"QueHTML"];;  if (![fileManager fileExistsAtPath:matPath1]) {    NSString *matString = [[NSBundle mainBundle] pathForResource:@"QueHTML" ofType:@"bundle"];    dispatch_async(dispatch_get_global_queue(0, 0), ^{      [fileManager removeItemAtPath:matPath1 error:nil];      [fileManager copyItemAtPath:matString toPath:matPath1 error:nil];      dispatch_async(dispatch_get_main_queue(), ^{        NSLog(@"創建完了");        if ([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0) {          [self ios8Load];        }        else{          [self ios9Load];        }      });    });  }  else{    if ([[[UIDevice currentDevice] systemVersion] floatValue] <9.0) {      [self ios8Load];    }    else{      [self ios9Load];    }  }}- (void)ios8Load {  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  NSString *path = [paths objectAtIndex:0];  NSString *basePath = [NSString stringWithFormat:@"%@/%@",path,@"QueHTML/"];  [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"www/QueHTML/index.html"]]]]];}- (void)ios9Load {  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  NSString *path = [paths objectAtIndex:0];  NSString *basePath = [NSString stringWithFormat:@"%@/%@",path,@"QueHTML/"];  NSString *htmlPath = [NSString stringWithFormat:@"%@/%@",path,@"QueHTML/index.html"];  NSURL *fileURL = [NSURL fileURLWithPath:htmlPath];  if (@available(iOS 9.0, *)) {    [self.wkWebView loadFileURL:fileURL allowingReadAccessToURL:[NSURL fileURLWithPath:basePath isDirectory:YES]];  }}實現代理方法
// 接收到服務器跳轉請求之后調用- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{  NSLog(@"接收到服務器跳轉請求----%@",navigation);}// 在收到響應后,決定是否跳轉- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{  NSLog(@"在收到響應后,決定是否跳轉---%@",navigationResponse.response.URL.absoluteString);  //允許跳轉  decisionHandler(WKNavigationResponsePolicyAllow);  //不允許跳轉  //decisionHandler(WKNavigationResponsePolicyCancel);}// 在發送請求之前,決定是否跳轉- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{  NSLog(@"在發送請求之前,決定是否跳轉---%@",navigationAction.request.URL.absoluteString);  //允許跳轉  decisionHandler(WKNavigationActionPolicyAllow);  //不允許跳轉  //decisionHandler(WKNavigationActionPolicyCancel);}#pragma mark - WKNavigationDelegate// 頁面開始加載時調用- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{  NSLog(@"頁面開始加載");}// 當內容開始返回時調用- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{  NSLog(@"內容開始返回");}// 頁面加載完成之后調用- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{  NSLog(@"頁面加載完成");}// 頁面加載失敗時調用- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{  NSLog(@"頁面加載失敗");}如果是https訪問需加上一下代碼
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {  if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {    if ([challenge previousFailureCount] == 0) {      NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];      completionHandler(NSURLSessionAuthChallengeUseCredential, credential);    } else {      completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);    }  } else {   completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);  }}總結
以上所述是小編給大家介紹的vue 項目 iOS WKWebView 加載,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
新聞熱點
疑難解答