IOS Cordova嵌套Cocos Creator的坑

最近在看如何把H5游戏嵌套发布在app上,于是用Cordova作为工具。

然而之前Cordova在IOS上是用UIWebview,但是IOS新版本上强制要用wkwebview。还好新版Cordova也支持了,但是遇到了一个坑,加载不了:

IOS Cordova嵌套Cocos Creator的坑

原因:
wkwebview对于文件的访问,也是认为是跨域的一种

解决办法:

一定要设置[configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
// 初始化webview
- (void)viewDidLoad {
    [super viewDidLoad];
    [self installStartTime];

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    self.webview = [[JSBWebView alloc] initWithFrame:self.view.bounds configuration:config];
    self.webview.navigationDelegate = self;
    self.webview.UIDelegate = self;
}

- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
{
    WKUserScript *script = [[WKUserScript alloc] initWithSource:[self jsString] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
    [configuration.userContentController addUserScript:script];
    [configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];

    self = [super initWithFrame:frame configuration:configuration];
    if (self) {
        [self setup];
    }
    return self;
}

参考资料:
https://www.jianshu.com/p/92432d11c6dc
https://stackoverflow.com/questions/40472796/wkwebview-loadfileurl-works-only-once

调整经过:

因为Cordova必须要在初始化之前给url,在iOS这边他叫startPage。

而Cordova的wkwebivew是必须获取startPage后才会初始化

所以我进去以后才能设定[self.wkWebView.configuration.preferences setValue:@YES]
此时再刷新一下就好了。

Cordova是隐藏掉[self.wkWebView loadRequest:requestObj];这个步骤的,没办法在loadrequest之前做设置,所以只能刷新,让他重新触发一次loadrequest

相关推荐