利用CocoaHTTPServer實現wifi區域網傳輸檔案到iphone
阿新 • • 發佈:2019-02-16
背景
近日在做一個程式碼閱讀器,其中涉及到程式碼檔案的上傳,之前看到過許多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