问题描述:
Cocos-js、CocosCreator打包web-mobile后,在WKWebView框架下运行,存在资源跨域问题,表现为资源加载不到,运行显示白屏。
解决方案:
在ViewController加入以下代码:
[configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
附上完整代码:
#import "ViewController.h"
#import <WebKit/WebKit.h>
#define KMainWidth ([UIScreen mainScreen].bounds.size.width)
#define KMainHeight ([UIScreen mainScreen].bounds.size.height)
@interface ViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property(nonatomic,strong)WKWebView *mainWebView;
@property(nonatomic,strong)UIButton *alertButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.mainWebView];
[self.view addSubview:self.alertButton];
self.view.backgroundColor = [UIColor whiteColor];
}
- (WKWebView *)mainWebView{
if (_mainWebView == nil) {
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userController = [[WKUserContentController alloc] init];
configuration.userContentController = userController;
configuration.allowsInlineMediaPlayback = YES;
configuration.mediaPlaybackRequiresUserAction = false;
[configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
_mainWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KMainWidth, KMainHeight) configuration:configuration];
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"index.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
[_mainWebView loadRequest: request];
_mainWebView.navigationDelegate = self;
_mainWebView.UIDelegate = self;
[userController addScriptMessageHandler:self name:@"currentCookies"];
}
return _mainWebView;
}
@end