【问题标题】:How to load css and js file from CacheDirectory with WKWebView?如何使用 WKWebView 从 CacheDirectory 加载 css 和 js 文件?
【发布时间】: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? 访问您的基本网址。

标签: ios objective-c uiwebview webkit wkwebview


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2017-11-28
    相关资源
    最近更新 更多