美文网首页
iOS WKWebView 加载本地html文件

iOS WKWebView 加载本地html文件

作者: 冰点雨 | 来源:发表于2020-08-05 15:28 被阅读0次

目录

561596612277_.pic.jpg

如下直接获取文件加载会报错:

NSString *mainBundlePath = [[NSBundle mainBundle]bundlePath];
    NSString *basePath = [NSString stringWithFormat:@"%@/editor",mainBundlePath];
    NSURL *baseUrl = [NSURL fileURLWithPath:basePath isDirectory:YES];
    NSString *htmlUrl = [NSString stringWithFormat:@"%@/index.html",basePath];
    NSString *html = [[NSString alloc] initWithContentsOfFile:htmlUrl encoding:NSUTF8StringEncoding error:nil];
    [self.wkWebView loadHTMLString:html baseURL:nil];

报错信息

输出插入结果 :Error Domain=WKErrorDomain Code=4 "发生JavaScript异常" UserInfo={WKJavaScriptExceptionLineNumber=64, WKJavaScriptExceptionMessage=ReferenceError: Can't find variable: $, WKJavaScriptExceptionColumnNumber=5, WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=发生JavaScript异常}

正确加载方式:

需要设置baseURL

//加载本地 html js 文件
    NSString *mainBundlePath = [[NSBundle mainBundle]bundlePath];
    NSString *basePath = [NSString stringWithFormat:@"%@/editor",mainBundlePath];
    NSURL *baseUrl = [NSURL fileURLWithPath:basePath isDirectory:YES];
    NSString *htmlUrl = [NSString stringWithFormat:@"%@/index.html",basePath];
    NSString *html = [[NSString alloc] initWithContentsOfFile:htmlUrl encoding:NSUTF8StringEncoding error:nil];
    [self.wkWebView loadHTMLString:html baseURL:baseUrl];

相关文章

网友评论

      本文标题:iOS WKWebView 加载本地html文件

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