背景
近日在做一個代碼閱讀器,其中涉及到代碼文件的上傳,之前看到過許多app支持局域網傳文件,因此就通過查詢和研究實現了此功能,我是用的框架是CocoaHTTPServer。
原理
CocoaHTTPServer框架能夠在iOS上建立起一個本地服務器,只要電腦和移動設備連入同一熱點,即可使用電腦訪問iOS服務器的頁面,利用POST實現文件的上傳。
實現
CocoaHTTPServer沒有現成的向iOS設備傳輸的Sample,我通過學習OS X端的Sample實現了iOS端的文件傳輸,按照下面的步驟配置即可。
1.下載CocoaHTTPServer
2.解壓後,將CocoaHTTPServer-master目錄下的Core導入工程。
3.打開Samples/SimpleFileUploadServer,將其中的MyHTTPConnection類文件、web文件夾導入工程。
4.打開Vendor,將其中的CocoaAsyncSocket、CocoaLumberjack文件夾導入。
所有要導入的文件如下圖所示:注意,其中的HYBIPHelper爲獲取本地ip的工具類,不是必要的,請忽視。
5.打開工程,打開MyHTTPConnection.m,根據標記#pragma mark multipart form data parser delegate
跳轉或者直接找到139行,- (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header
方法,將其中filePath的值修改爲iOS的某個目錄,這個路徑是上傳的文件存儲的路徑,這裏以Caches爲例:
// NSString* uploadDirPath = [[config documentRoot] stringByAppendingPathComponent:@"upload"];
NSString *uploadDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
6.在適當的地方配置server啓動,這裏以AppDelegate爲例:
#import "AppDelegate.h"
#import "HTTPServer.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import "MyHTTPConnection.h"
@interface AppDelegate (){
HTTPServer *httpServer;
}
@end
@implementation 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;
}
@end
7.運行後,在控制檯打印出端口號,再通過路由器或者熱點工具查詢設備的內網ip,通過ip:port訪問即可,如果成功,會看到如下頁面:
8.如果上傳成功,在控制檯會打印存儲到的位置,可以通過打開沙盒來驗證。
補充
一般的局域網傳文件,都會顯示ip:port,以方便用戶訪問,要實現設備內網ip的獲取,可以用下面的代碼,這段代碼來自標哥-iOS攻城獅,具體內容如下:
//
// HYBIPHelper.h
// XiaoYaoUser
//
// Created by 黃儀標 on 14/12/9.
// Copyright (c) 2014年 xiaoyaor. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface HYBIPHelper : NSObject
/*!
* get device ip address
*/
+ (NSString *)deviceIPAdress;
@end
//
// HYBIPHelper.m
// XiaoYaoUser
//
// Created by 黃儀標 on 14/12/9.
// Copyright (c) 2014年 xiaoyaor. All rights reserved.
//
#import "HYBIPHelper.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
@implementation HYBIPHelper
+ (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