美文网首页
iOS WKWebView无法加载本地css文件问题

iOS WKWebView无法加载本地css文件问题

作者: 帅气影中人 | 来源:发表于2018-02-24 16:41 被阅读0次

    最近学习Hybrid APP混合开发,为了性能及流畅度,将UIWebView替换为WKWebView,模拟器测试一切良好,但真机上遇到了一个大问题:CSS文件未被加载


    未读取css文件

    网上一通查阅及验证后,没有一个可行方案😭,大致代码如下

        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:方法的系统文案,看了简介真实欲哭无泪啊

    /*! @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只加载此文件,如果引用一个目录,则会加载整个文件夹的内容
    • 因此只需要改成以下代码
       if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
            NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
            NSURL *direUrl = [NSURL fileURLWithPath:@".html所在目录名"];
            [self.webView loadFileURL:fileUrl allowingReadAccessToURL: direUrl];
        }
    

    成功


    读取css成功

    这是一个悲伤地故事,告诉了我们多看系统文档!!

    相关文章

      网友评论

          本文标题:iOS WKWebView无法加载本地css文件问题

          本文链接:https://www.haomeiwen.com/subject/cdzqxftx.html