緣起:
一個(gè)朋友給我一份HTML寫的游戲代碼,想要跑到iOS上击蹲,做成原生應(yīng)用署拟。很簡單嘛,開個(gè)工程歌豺,拖一個(gè)WKWebView芯丧,加載本地HTML,一氣呵成世曾。但是缨恒。谴咸。。黑屏骗露!查看代碼發(fā)現(xiàn)
<script>
// Issue a warning if trying to preview an exported project on disk.
(function(){
// Check for running exported on file protocol
if (window.location.protocol.substr(0, 4) === "file")
{
alert("Exported games won't work until you upload them. (When running on the file:/// protocol, browsers block many features from working for security reasons.)");
}
})();
</script>
不支持本地加載岭佳。。萧锉。
但是總不能為這個(gè)游戲買個(gè)域名空間珊随,做個(gè)后臺吧。于是我就想能不能再iPhone上搭建一個(gè)服務(wù)器柿隙,直接請求本地呢叶洞,就像Django一樣,于是禀崖,我打開了邪惡的百度(hosts不能用了衩辟。。波附。)
解決方案:
果然互聯(lián)網(wǎng)上資源多啊艺晴,早在好幾年前就有人這么做了,并且開源了掸屡,就是CocoaHTTPServer封寞,但是時(shí)間長了,不支持Pod仅财,于是search了一下狈究,有一個(gè)支持了pod的開源,叫CVCocoaHTTPServeriOS盏求。按照說明谦炒,這個(gè)庫支持OSX,iOS:
1风喇、Built in support for bonjour broadcasting
2宁改、IPv4 and IPv6 support
3、Asynchronous networking using GCD and standard sockets
4魂莫、Password protection support
5还蹲、SSL/TLS encryption support
6、Extremely FAST and memory efficient
7耙考、Extremely scalable (built entirely upon GCD)
8谜喊、Heavily commented code
9、Very easily extensible
10倦始、WebDAV is supported too!
emmmm...姿勢很多斗遏,聽說有人用這個(gè)做出了迅雷WiFi傳片的功能,這里暫時(shí)用不到鞋邑,只是用來加載本地資源诵次。
實(shí)現(xiàn):
于是用pod加載了CocoaHTTPServer账蓉,引入頭文件,在AppDelegate里開啟服務(wù)器逾一,并且記錄隨機(jī)分配的端口號:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self configLocalHttpServer];
return YES;
}
#pragma mark - 搭建本地服務(wù)器 并且啟動
- (void)configLocalHttpServer{
self.localHttpServer = [[HTTPServer alloc] init];
[self.localHttpServer setType:@"_http.tcp"];
//指定服務(wù)器的目錄铸本,以后請求資源就在這個(gè)目錄里,這個(gè)目錄拖拽進(jìn)來的時(shí)候要選Create folder references,是一個(gè)藍(lán)色文件夾
NSString * webLocalPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"5"];
[self.localHttpServer setDocumentRoot:webLocalPath];
[self startServer];
}
- (void)startServer
{
NSError *error;
if([self.localHttpServer start:&error]){
self.port = [NSString stringWithFormat:@"%d",[self.localHttpServer listeningPort]];
}
else{
}
}
這里端口號如果沒有指定的話遵堵,會隨機(jī)分配一個(gè)箱玷,也可以在啟動服務(wù)器的時(shí)候指定一個(gè)端口號:
[self.localHttpServer setPort:6000];
服務(wù)器啟動以后就可以加載網(wǎng)頁了,像這樣:
AppDelegate *appd = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSString *port = appd.port;
if (nil == port) {
return NO;
}
NSString *str = [NSString stringWithFormat:@"http://localhost:%@", port];
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
因?yàn)槲业亩丝谔柺请S機(jī)分配的陌宿,所以這里引入了AppDelegate锡足。加載http://localhost拼接你的端口號,默認(rèn)會加載剛才的資源目錄里的index.html文件壳坪,此時(shí)舶得,游戲就已經(jīng)可以跑起來了!如果你是模擬器運(yùn)行弥虐,還可以用Mac上的瀏覽器扩灯,打開http://localhost拼接你的端口號媚赖,就可以訪問你的iPhone 上的服務(wù)器了霜瘪!
總結(jié):
由于iOS程序不能常駐后臺,想要在后臺也開啟惧磺,就需要用定位功能或者其他的后臺模式颖对。總的來說磨隘,能在iPhone上實(shí)現(xiàn)一個(gè)服務(wù)器缤底,后續(xù)可以想象的空間很大啊番捂!