搭建手機本地服務器,可以保存在iOS沙盒中,從沙盒去獲取存在本地的html,配置文件和證書文件的安裝,從而本地配置信息,不走服務器,更加快速配置使用配置文件和頁面的展示
用到的框架?RoutingHTTPServer ?
添加這些文件
編譯沒有出錯的情況下就開始搭建了
在appdelegate導入頭文件
#import "RoutingHTTPServer.h"
添加屬性
@property (strong, nonatomic , readonly)RoutingHTTPServer *httpServer;
在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions ;中添加開啟服務器的代碼
// Create server using our custom MyHTTPServer class
_httpServer = [[RoutingHTTPServer alloc] init];
/* * * * * * * * *? add By AK? * * * * * * * * * * * * * */
/*? ? ? 設置文件格式為 Apple.mobileconfig? ? ? */
[_httpServer setDefaultHeader:@"Content-Type" value:@"application/x-apple-aspen-config"];
[_httpServer setType:@"_http._tcp."];
[_httpServer setPort:8000];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[_httpServer setDocumentRoot:documentsDirectory];
NSLog(@"%d",_httpServer.isRunning);
if (_httpServer.isRunning){
[_httpServer stop];
};
NSError *error;
if([_httpServer start:&error]) {
NSLog(@"Started HTTP Server on port %hu", [_httpServer listeningPort]);
} else {
NSLog(@"Error starting HTTP Server: %@", error);
[self startServer];
}
其中端口號在測試的時候必須添加端口才可以使用,
在加載描述文件,所以添加類型
把你對應的文件存放在對應的沙盒中
使用UIApplication 來用safari 來啟動你所使用的html文件或者是描述文件
NSURL *url1 = [NSURL URLWithString:@"http://127.0.0.1:8000/pptp1.html"];
if([[UIApplication sharedApplication] canOpenURL:url1]){
[[UIApplication sharedApplication] openURL:url1];
}
問題:
當程序在后臺的時候,從后臺調(diào)出app可能導致服務器斷開,但服務器卻無法檢測
再次調(diào)用url會出現(xiàn)無法訪問服務器
解決1:添加一個UIBackgroundTaskIdentifier來讓app進入后臺的時候運行一段時間
在app delegate中
@property (nonatomic, unsafe_unretained)UIBackgroundTaskIdentifier bgTask;
在- (void)applicationDidEnterBackground:(UIApplication *)application中添加
if(!_bgTask) {
_bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
[application endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
});
}];
}
問題2:可能時間過長還是導致服務器失效
無效,服務器是正常的,沒有斷開連接.
我解決的辦法
在- (void)applicationDidEnterBackground:(UIApplication *)application
app進入后臺的時候關閉服務器,調(diào)用
[_httpServer stop];
當app進入前臺- (void)applicationDidBecomeActive:(UIApplication *)application
再次開啟
NSError *error;
if([_httpServer start:&error]) {
NSLog(@"Started HTTP Server on port %hu", [_httpServer listeningPort]);
} else {
NSLog(@"Error starting HTTP Server: %@", error);
// Probably should add an escape - but in practice never loops more than twice (bug filed on GitHub https://github.com/robbiehanson/CocoaHTTPServer/issues/88)
[self startServer];
}