转贴至:https://www.jianshu.com/p/cde0f77d2f63
1、移动端何时需要搭建本地服务器?
当移动端与web端需要很强很即时的数据交互时,服务端只需要一个结果的时候,在移动端搭建本地服务器,然后让移动端与web端交互,完成一系列动作,把结果告诉服务端,实际应用场景:积分墙。
2、如何在移动端搭建本地服务器?
(不知道怎么才能让我自己发布的资源免费)
可以在csdn下载:https://download.csdn.net/download/u012717715/11149867
也可以在git找资源,都是免费的
//导入头文件
#import "RoutingHTTPServer.h"
#pragma mark -- 开启本地服务
-(void)openServer{
self.http = [[RoutingHTTPServer alloc] init];
// Set a default Server header in the form of YourApp/1.0
NSDictionary *bundleInfo = [[NSBundle mainBundle] infoDictionary];
NSString *appVersion = [bundleInfo objectForKey:@"CFBundleShortVersionString"];
if (!appVersion) {
appVersion = [bundleInfo objectForKey:@"CFBundleVersion"];
}
NSString *serverHeader = [NSString stringWithFormat:@"%@/%@",
[bundleInfo objectForKey:@"CFBundleName"],
appVersion];
[self.http setDefaultHeader:@"Server" value:serverHeader];
[self.http setDefaultHeader:@"Content-Type" value:@"text/plain"];
[self.http setPort:55433];
[self.http setDocumentRoot:[@"~/Sites" stringByExpandingTildeInPath]];
[self setupRoutes];
NSError *error;
if ([self.http start:&error]) {
NSLog(@"开启成功了");
}
}
3、如何设置路由,与web交互?
#pragma mark -- 配置路由
- (void)setupRoutes {
[self.http post:@"/" withBlock:^(RouteRequest *request, RouteResponse *response) {
[response setHeader:@"Access-Control-Allow-Origin" value:@"*"];
//请求参数
NSDictionary *dicJson=[NSJSONSerialization JSONObjectWithData:[request body] options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dicJson);
if ([dicJson[@"type"] isEqualToString:@"check"]) {
//响应
[response respondWithString:dicJson[@"userId"]];
}
}];
}
4、如何保持移动端后台不被kill?
(现阶段的iOS 这些代码已经申请不到多少时间了,过几分钟就会被强制kill掉)
-(void)applicationDidEnterBackground:(UIApplication *)application{
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
}
-(void)applicationWillEnterForeground:(UIApplication *)application {
[[UIApplication sharedApplication] endBackgroundTask:UIBackgroundTaskInvalid];
}
扫描二维码关注公众号,回复:
6128068 查看本文章
5、web端代码