iOS中使用WKWebView加载本地h5小游戏资源的做法

2020-07-22  本文已影响0人  iOS_沧海一笑

前言:由于我现在做的工作就是每天写游戏SDK,混淆代码,想各种办法将H5游戏上架到App Store上,由于苹果审核特别严,所以我们得想办法绕开苹果的审核。我们就使用WKWebView加载H5小游戏,通过将H5小游戏打包成资源放到本地进行加载的方式让苹果审核。废话不多说,接下来看代码实现:

pod 'CocoaHTTPServer', '~> 2.3'
pod 'SSZipArchive'
image.png

代码具体实现

@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;
}
- (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游戏的资源打包到本地进行加载了!

上一篇下一篇

猜你喜欢

热点阅读