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

时间:2016-09-08 07:32:29

标签: ios objective-c uiwebview webkit wkwebview

我想从cacheDirectory中加载html文件(file:////Library/Cache/sample1_web/index.html),并在WKWebView中使用css和js文件。但是,它没有在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

1 个答案:

答案 0 :(得分:0)

如果您的资源是压缩的,并且只在加载HTML时将它们解压缩到内存(而不是在文件系统上),那么您的JavaScript和CSS文件仍会被压缩并且{{1标签无效,因为<script src="js/script.js">路径不存在。

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