rkv
rkv

Reputation: 118

How to load css and js file from CacheDirectory with WKWebView?

I want load html file (file:////Library/Cache/sample1_web/index.html) from cacheDirectory with css and js files in WKWebView. But, it's not load css and js files in WKWebView.

I load with method: 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];
}

And, perfect load html but not with css and js. What is the problem? And I tried with UIWebView load this html and success load html with css and js.

And I check:

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

Upvotes: 0

Views: 944

Answers (1)

paulvs
paulvs

Reputation: 12053

If your resources are zipped, and you only unzip them in memory (not on the file system) when loading the HTML, your JavaScript and CSS files remain zipped and the paths in your <script src="js/script.js"> tags will not be valid because the src paths don't exist.

You need to unzip the whole directory so that all your resources are visible to each other.

Upvotes: 0

Related Questions