uniapp

WKWebView 加载 Uni-App 导出的本地 H5

2022-08-08  本文已影响0人  韦弦Zhy

Uni-App 打包发布的H5包直接放到APP中加载可以用于提升加载速度,一般有两种方式:

加载步骤

一、创建一个uni-app项目,并打包成H5

二、iOS项目内直接加载包内 Uni-App

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSString *pathString = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"h5"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:pathString]];
    [self.webView loadRequest:request];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSString *pathString = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"h5"];
    NSString *pathString2 = [[NSString stringWithFormat:@"?id=%@",@"testId"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    NSURL *baseUrl = [NSURL fileURLWithPath:pathString];
    NSURL *loadUrl = [NSURL URLWithString:pathString2 relativeToURL:baseUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:loadUrl];
    
    [self.webView loadRequest:request];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    NSString *pathString = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"h5"];
    NSString *pathString2 = @"#/pages/component/view/view";

    NSURL *baseUrl = [NSURL fileURLWithPath:pathString];
    NSURL *loadUrl = [NSURL URLWithString:pathString2 relativeToURL:baseUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:loadUrl];

    [self.webView loadRequest:request];
}

三、加载沙盒内Uni-App

基本逻辑和加载本地一致,但是必须使用 relativeToUrl 方法加载,首先确认自己缓存的目录,然后给路径拼接file://协议头:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = [[paths objectAtIndex:0] stringByAppendingString:@"h5"];
    
    NSString *path = [basePath stringByAppendingString:@"index.html"];
    
    NSURL *baseUrl = [NSURL fileURLWithPath:basePath];
    
    // 需要手动拼接 file://
    NSString *loadPath = [[NSString stringWithFormat:@"file://%@",path] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    // 最终加载路径
    NSURL *loadUrl = [NSURL URLWithString:loadPath relativeToURL:baseUrl];
    
    [self.webView loadFileURL:loadUrl allowingReadAccessToURL:[NSURL fileURLWithPath: [paths objectAtIndex:0]]];
}
iOS 加载Uni-APP 效果

Tips: 打包出来的H5先用电脑试下能否成功加载 index.html ~

如果是Origin null is not allowed by Access-Control-Allow-Origin.问题导致无法加载可以按如下设置,使WKWebView允许跨域:

[self.webView.configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
上一篇 下一篇

猜你喜欢

热点阅读