如何使用 WKWebView 从 CacheDirectory 加载 css 和 js 文件?

Posted

技术标签:

【中文标题】如何使用 WKWebView 从 CacheDirectory 加载 css 和 js 文件?【英文标题】:How to load css and js file from CacheDirectory with WKWebView? 【发布时间】:2016-09-08 07:32:29 【问题描述】:

我想在 WKWebView 中使用 css 和 js 文件从 cacheDirectory 加载 html 文件 (file:////Library/Cache/sample1_web/index.html)。但是,它不会在 WKWebView 中加载 css 和 js 文件。

我用方法加载:loadHTMLString:baseURL

- (void)viewDidLoad 
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

_webView = [[WKWebView alloc] initWithFrame:self.view.frame];

NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample1_web.zip"];
NSString *destPath = [self getCachePath];

if ([SSZipArchive unzipFileAtPath:filePath toDestination:destPath]) 
    NSLog(@"SUCCESS unzip!");

    NSError *erno = nil;
    NSString *urlHTML = [[self getCachePath] stringByAppendingString:@"/sample1_web/index.html"];
    NSString *contentFile = [NSString stringWithContentsOfFile:urlHTML encoding:NSUTF8StringEncoding error:&erno];
    NSURL *urlBase = [[NSBundle bundleWithPath:[[self getCachePath] stringByAppendingPathComponent:@"sample1_web"]] bundleURL];

    NSLog(@"@%@", urlBase);
    NSLog(@"@%@", contentFile);
    if (erno == nil) 
        [_webView loadHTMLString:contentFile baseURL:urlBase];
    else
        NSLog(@"%@", erno);

 else 
    NSLog(@"FAILED unzip...");


[self.view addSubview:_webView];




- (void)didReceiveMemoryWarning 
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    

- (NSString *)getCachePath 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];

而且,完美加载 html 但不使用 css 和 js。问题是什么?我尝试用 UIWebView 加载这个 html 并成功用 css 和 js 加载 html。

我检查一下:

-https://forums.xamarin.com/discussion/61891/wkwebview-load-local-content-with-loadfileurl -WkWebView won't loadHTMLstring

【问题讨论】:

试试这个 API func loadFileURL(_ URL: URL, allowingReadAccessTo readAccessURL: URL) -> WKNavigation? 访问您的基本网址。 【参考方案1】:

如果您的资源已压缩,并且您仅在加载 HTML 时将它们在内存中(而不是在文件系统上)解压缩,则您的 javascript 和 CSS 文件将保持压缩状态,并且您的 <script src="js/script.js"> 中的路径标签将无效,因为 src 路径不存在。

您需要解压缩整个目录,以便您的所有资源彼此可见。

【讨论】:

以上是关于如何使用 WKWebView 从 CacheDirectory 加载 css 和 js 文件?的主要内容,如果未能解决你的问题,请参考以下文章

如何从 WKWebView 获取 cookie?

如何从 WKWebView 启用和获取 cookie?

IOS - 如何从 WKWebView 获取缓存的资源?

如何使用 WKWebview 从 iPad 的 Document 目录加载 javascript 和 css 资源?

如何从 WKWebView 打印特定的 iFrame

如何编辑从 WKWebView 显示的键盘附件视图?