最近學習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)文檔!!