iOS WKWebView無法加載本地css文件問題

最近學習Hybrid APP混合開發(fā),為了性能及流暢度,將UIWebView替換為WKWebView,模擬器測試一切良好,但真機上遇到了一個大問題:CSS文件未被加載


未讀取css文件

網(wǎng)上一通查閱及驗證后,沒有一個可行方案??,大致代碼如下

    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
        [self.webView loadFileURL:fileUrl allowingReadAccessToURL:fileUrl];
    }else{
        
        NSURL *fileURL = [self fileURLForBuggyWKWebView8:[NSURL fileURLWithPath:filePath]];
        NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
        [self.webView loadRequest:request];
    }

// 將文件copy到tmp目錄,iOS8及以下使用
- (NSURL *)fileURLForBuggyWKWebView8:(NSURL *)fileURL {
    NSError *error = nil;
    if (!fileURL.fileURL || ![fileURL checkResourceIsReachableAndReturnError:&error]) {
        return nil;
    }
    // Create "/temp/www" directory
    NSFileManager *fileManager= [NSFileManager defaultManager];
    NSURL *temDirURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:@"www"];
    [fileManager createDirectoryAtURL:temDirURL withIntermediateDirectories:YES attributes:nil error:&error];
    
    NSURL *dstURL = [temDirURL URLByAppendingPathComponent:fileURL.lastPathComponent];
    // Now copy given file to the temp directory
    [fileManager removeItemAtURL:dstURL error:&error];
    [fileManager copyItemAtURL:fileURL toURL:dstURL error:&error];
    // Files in "/temp/www" load flawlesly :)
    return dstURL;
}

我的手機是iOS11,所以也沒驗證iOS8使用方法的正確性
在我快要絕望的時候,靈光一閃點進了loadFileURL:(NSURL *)URL allowingReadAccessToURL:方法的系統(tǒng)文案,看了簡介真實欲哭無淚啊

/*! @abstract Navigates to the requested file URL on the filesystem.
 @param URL The file URL to which to navigate.
 @param readAccessURL The URL to allow read access to.
 @discussion If readAccessURL references a single file, only that file may be loaded by WebKit.
 If readAccessURL references a directory, files inside that file may be loaded by WebKit.
 @result A new navigation for the given file URL.
 */
 

大概意思:

  • 第一個URL指將要導航的地址
  • 第二個URL如果引用單個文件則webkit只加載此文件,如果引用一個目錄,則會加載整個文件夾的內(nèi)容
  • 因此只需要改成以下代碼
   if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
        NSURL *direUrl = [NSURL fileURLWithPath:@".html所在目錄名"];
        [self.webView loadFileURL:fileUrl allowingReadAccessToURL: direUrl];
    }

成功


讀取css成功

這是一個悲傷地故事,告訴了我們多看系統(tǒng)文檔!!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容