前言:由于我現(xiàn)在做的工作就是每天寫游戲SDK,混淆代碼目代,想各種辦法將H5游戲上架到App Store上塔橡,由于蘋果審核特別嚴(yán)佳镜,所以我們得想辦法繞開蘋果的審核裆馒。我們就使用
WKWebView
加載H5小游戲姊氓,通過將H5小游戲打包成資源放到本地進行加載的方式讓蘋果審核。廢話不多說喷好,接下來看代碼實現(xiàn):
- 首先我們要搭建一個第三方本地服務(wù)器翔横,具體要使用到的第三方,在
pod
中如下引入:
pod 'CocoaHTTPServer', '~> 2.3'
pod 'SSZipArchive'
- 在導(dǎo)入
CocoaHTTPServer
庫后梗搅,編譯會報錯禾唁,具體解決方案請看這篇文章(http://www.reibang.com/p/b693d660acc1)
代碼具體實現(xiàn)
- 在
AppDelegate中didFinishLaunchingWithOptions
方法中調(diào)用setupLocalHttpServer
,我們首先要導(dǎo)入#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
里面調(diào)用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游戲的資源打包到本地進行加載了荡短!