前言:由于我现在做的工作就是每天写游戏SDK,混淆代码,想各种办法将H5游戏上架到App Store上,由于苹果审核特别严,所以我们得想办法绕开苹果的审核。我们就使用
WKWebView
加载H5小游戏,通过将H5小游戏打包成资源放到本地进行加载的方式让苹果审核。废话不多说,接下来看代码实现:
- 首先我们要搭建一个第三方本地服务器,具体要使用到的第三方,在
pod
中如下引入:
pod 'CocoaHTTPServer', '~> 2.3'
pod 'SSZipArchive'
- 在导入
CocoaHTTPServer
库后,编译会报错,具体解决方案请看这篇文章(//www.greatytc.com/p/b693d660acc1)
代码具体实现
- 在
AppDelegate中didFinishLaunchingWithOptions
方法中调用setupLocalHttpServer
,我们首先要导入#import <HTTPServer.h>, #import <SSZipArchive.h>
,定义两个属性:
@property (nonatomic, strong) HTTPServer *localHttpServer;
@property (nonatomic, copy) NSString *port;
- (void)setupLocalHttpServer{
_localHttpServer = [[HTTPServer alloc] init];
[_localHttpServer setType:@"_http.tcp"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
// 获取zip文件的路径
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"tiaotiaoxiaoemo" ofType:@"zip"];
// zip解压缩后的路径
NSString *webPath = [self uSSZipArchiveWithFilePath:filePath];
if (![fileManager fileExistsAtPath:webPath]){
NSLog(@"File path error!");
}else{
NSString *webLocalPath = webPath;
[_localHttpServer setDocumentRoot:webLocalPath];
[self hjss_startServer];
}
}
- (void)hjss_startServer
{
NSError *error;
if([_localHttpServer start:&error]){
self.port = [NSString stringWithFormat:@"%d",[_localHttpServer listeningPort]];
NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
[accountDefaults setObject:self.port forKey:@"webPort"];
[accountDefaults synchronize];
}
else{
}
}
-(NSString *)uSSZipArchiveWithFilePath:(NSString *)path
{
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
NSString *destinationPath =[cachesPath stringByAppendingPathComponent:@"SSZipArchive"];
BOOL isSuccess = [SSZipArchive unzipFileAtPath:path toDestination:destinationPath];
if (isSuccess) {
NSString *path = [self obtainZipSubsetWithFilePath:destinationPath];
return path;
}
return @"";
}
- (NSString *)obtainZipSubsetWithFilePath:(NSString *)path
{
NSString *destinationPath = [path stringByAppendingPathComponent:@"tiaotiaoxiaoemo"];
return destinationPath;
}
- 在你要加载H5游戏的控制器中,首先定义一个
webView
的属性:在viewDidLoad
里面调用gotoStartGame
- (void)gotoStartGame {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSURL *pathStr = [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:%@", [userDefaults objectForKey:@"webPort"]]];
NSURLRequest *request = [NSURLRequest requestWithURL:pathStr];
[self.webView loadRequest:request];
}
这样就可以通过webView
将H5游戏的资源打包到本地进行加载了!