iOS WKWebview加载本地Vue前端项目

Vue中vue.config.js配置如下:

vue2
module.exports = {
  publicPath: './',
}

vue3
module.exports = {
  base: './',
}

打包出来将前端静态文件放到iOS项目中


image.png

将assets文件夹导入到原生项目时一定注意导入方式


image.png

导入成功后在项目中为蓝色文件夹
image.png

webView加载

- (void)configWebView {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"assets/html"];
    NSURL *pathURL = [NSURL fileURLWithPath:filePath];
    NSURL *baseURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/assets/html",[NSBundle mainBundle].bundlePath] isDirectory:YES];
    [self.webview loadFileURL:pathURL allowingReadAccessToURL:baseURL];
}

如果Vue页面有路由

- (void)configWebView {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"assets/html"];
    NSURL *htmlURL = [NSURL fileURLWithPath:filePath];
    NSURL *pathURL = [NSURL URLWithString:@"#/login" relativeToURL:htmlURL];
    NSURL *baseURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/assets/html",[NSBundle mainBundle].bundlePath] isDirectory:YES];
    [self.webview loadFileURL:pathURL allowingReadAccessToURL:baseURL];
}

不过webview加载本地前端项目经常会遇到前端跨域,这就是另外一个故事了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容