1. 程式人生 > >wkwebview加載本地html的要點

wkwebview加載本地html的要點

webview load 過程 nbu 文件路徑 9.png nsstring code cimage

項目中有些頁面,我采用了html頁面開發,然後用wkwebview加載的設計。在加載過程中遇見了一些問題,在這裏進行一些記載和討論。如有不同意見歡迎進行評論溝通。
問題時候這樣的:
在webview的loadrequest中不能加載出來
webview.m中的代碼:
//self.PageUrlString:加載的鏈接地址

 if (self.PageUrlString) {
         [self.wekView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.PageUrlString]]];
    }
獲取html的代碼:
  1. pathForResource

    webVC.PageUrlString = [[NSBundle mainBundle] pathForResource:@"connectUs" ofType:@"html"]
結果:並不能正常加載,如下圖

技術分享圖片

經過研究,換用了獲取文件路徑的方法,就可以正常加載了

2.URLForResource

 webVC.fileUrl = [[NSBundle mainBundle] URLForResource:@"connectUs.html" withExtension:nil];

討論

1.pathForResource 和 2.URLForResource 獲取結果的區別

打印結果
技術分享圖片

結果中可以看出來,

1.pathForResource 出來的結果是純路徑
2.URLForResource 出來的加file協議的路徑

結論:

wkwebview 中loadrequest加載的url應該是是設置協議的路徑

調整:

  webVC.PageUrlString = [NSString stringWithFormat:@"file://%@",[[NSBundle mainBundle] pathForResource:@"connectUs" ofType:@"html"]];

  webVC.fileUrl = [[NSBundle mainBundle] URLForResource:@"connectUs.html" withExtension:nil];

wkwebview加載本地html的要點