前幾天開會leader 說,測試一下iOS設備搭建局域網(wǎng)服務器.數(shù)據(jù)傳輸?shù)母黜椫笖?shù).于是開始了CocoaHTTPServer的學習之路,并在網(wǎng)上參考了各位大佬的教程.
原理:
利用CocoaHTTPServer框架能夠在iOS上建立起一個本地服務器趋翻,只要電腦/手機(iOS和Android都可以)和移動設備連入同一熱點届良,即可使用電腦訪問iOS服務器的頁面鸥滨,利用POST實現(xiàn)文件的上傳。
實現(xiàn):1.下載CocoaHTTPServer
2.解壓后挥唠,將CocoaHTTPServer-master目錄下的Core導入工程。
3.打開Samples/SimpleFileUploadServer脏里,將其中的MyHTTPConnection類文件壳猜、web文件夾導入工程。
4.打開Vendor氓癌,將其中的CocoaAsyncSocket谓谦、CocoaLumberjack文件夾導入。
5.打開工程贪婉,打開MyHTTPConnection.m反粥,根據(jù)標記#pragma mark multipart form data parser delegate跳轉(zhuǎn)或者直接找到139行,- (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header方法,將其中filePath的值修改為iOS的某個目錄才顿,這個路徑是上傳的文件存儲的路徑莫湘,這里以Caches為例:
NSString *uploadDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
6.在適當?shù)牡胤脚渲胹erver啟動,這里以AppDelegate為例:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
httpServer = [[HTTPServer alloc] init];
[httpServer setType:@"_http._tcp."];
// webPath是server搜尋HTML等文件的路徑
NSString *webPath = [[NSBundle mainBundle] resourcePath];
[httpServer setDocumentRoot:webPath];
[httpServer setConnectionClass:[MyHTTPConnection class]];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController = [[UIViewController alloc] init];
[self.window makeKeyAndVisible];
NSError *err;
if ([httpServer start:&err]) {
NSLog(@"port %hu",[httpServer listeningPort]);
}else{
NSLog(@"%@",err);
}
return YES;
}
7.運行后郑气,在控制臺打印出端口號幅垮,再通過路由器或者熱點工具查詢設備的內(nèi)網(wǎng)ip,通過ip:port訪問即可尾组,如果成功.如果不知道怎么樣獲得IP
請看下面
.h?
#import@interface CSMIPHelper : NSObject
+ (NSString *)deviceIPAdress;
@end
.m 文件
#import "CSMIPHelper.h"#include#include#include@implementation CSMIPHelper
+ (NSString *)deviceIPAdress {
NSString *address = @"an error occurred when obtaining ip address";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0) { // 0 表示獲取成功
temp_addr = interfaces;
while (temp_addr != NULL) {
if( temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
return address;
}
@end
8. 如果上傳成功忙芒,就把文件上傳到您的iPhone了。
總結(jié):經(jīng)過測試發(fā)現(xiàn),搭建的局域網(wǎng)可支持上傳各類型文件,上傳速度和局域網(wǎng)信號質(zhì)量有關(guān),如果使用手機熱點創(chuàng)建局域網(wǎng),不會消耗手機流量. 個人熱點的有效距離在15米左右,可同時支持多臺設備連接局域網(wǎng)進行上傳.