iPhone上搭建简单服务器

缘起:

一个朋友给我一份HTML写的游戏代码,想要跑到iOS上,做成原生应用。很简单嘛,开个工程,拖一个WKWebView,加载本地HTML,一气呵成。但是。。。黑屏!查看代码发现

    <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>

不支持本地加载。。。

但是总不能为这个游戏买个域名空间,做个后台吧。于是我就想能不能再iPhone上搭建一个服务器,直接请求本地呢,就像Django一样,于是,我打开了邪恶的百度(hosts不能用了。。。)

解决方案:

果然互联网上资源多啊,早在好几年前就有人这么做了,并且开源了,就是CocoaHTTPServer,但是时间长了,不支持Pod,于是search了一下,有一个支持了pod的开源,叫CVCocoaHTTPServeriOS。按照说明,这个库支持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...姿势很多,听说有人用这个做出了迅雷WiFi传片的功能,这里暂时用不到,只是用来加载本地资源。

实现:

于是用pod加载了CocoaHTTPServer,引入头文件,在AppDelegate里开启服务器,并且记录随机分配的端口号:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [self configLocalHttpServer];
    return YES;
}
#pragma mark - 搭建本地服务器 并且启动
- (void)configLocalHttpServer{
    self.localHttpServer = [[HTTPServer alloc] init];
    [self.localHttpServer setType:@"_http.tcp"];
    //指定服务器的目录,以后请求资源就在这个目录里,这个目录拖拽进来的时候要选Create folder references,是一个蓝色文件夹
    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{

    }
}

这里端口号如果没有指定的话,会随机分配一个,也可以在启动服务器的时候指定一个端口号:

[self.localHttpServer setPort:6000];

服务器启动以后就可以加载网页了,像这样:

    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];

因为我的端口号是随机分配的,所以这里引入了AppDelegate。加载http://localhost拼接你的端口号,默认会加载刚才的资源目录里的index.html文件,此时,游戏就已经可以跑起来了!如果你是模拟器运行,还可以用Mac上的浏览器,打开http://localhost拼接你的端口号,就可以访问你的iPhone 上的服务器了!

总结:

由于iOS程序不能常驻后台,想要在后台也开启,就需要用定位功能或者其他的后台模式。总的来说,能在iPhone上实现一个服务器,后续可以想象的空间很大啊!

Demo在此

本文来自网络,不代表本站立场,转载请注明出处:万道一,Wonder One » iPhone上搭建简单服务器
莫要搞事情哦
你喜欢的人刚好也未喜欢你
张学友刘德华邓紫琪已关注
赞(0) 打赏

赏点小费吧客倌

微信扫一扫打赏