背景

近日在做一个代码阅读器,其中涉及到代码文件的上传,之前看到过许多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

最新文章

  1. 【WPF系列】基础学习-WPF设计模式概览
  2. openjudge ROADS
  3. .NET在后置代码中输入JS提示语句(背景不会变白)
  4. 用C#中的params关键字实现方法形参个数可变
  5. UFLDL教程之(三)PCA and Whitening exercise
  6. mysql 基础技术
  7. HYSBZ1588 营业额统计【Splay】
  8. linux中添加环境变量(python为例)
  9. Oozie调用Spark实例
  10. Java数据持久层框架 MyBatis之API学习二(入门)
  11. 分布式一致性协议Raft原理与实例
  12. springMVC整理02--常用注解的使用
  13. Jmeter使用之-断言
  14. Cobbler安装CentOS7系统时报错 curl:(7)Failed connect to 10.0.0.201:80;Connection refused
  15. 没有内涵段子可以刷了,利用Python爬取段友之家贴吧图片和小视频(含源码)
  16. 【Hive学习之二】Hive SQL
  17. 雷林鹏分享:jQuery EasyUI 数据网格 - 创建子网格
  18. transclude
  19. 8 种 NoSQL 数据库系统对比(转自: http://blog.jobbole.com/1344/)
  20. SVM的基础原理

热门文章

  1. Python 内置方法
  2. luogu2252 取石子游戏
  3. codefroces 612E Square Root of Permutation
  4. codeforces 842C Ilya And The Tree
  5. 洛谷mNOIP模拟赛Day2-入阵曲
  6. ●POJ 2187 Beauty Contest
  7. 2015 多校联赛 ——HDU5386(暴力)
  8. UVA 12161 Ironman Race in Treeland
  9. Mysql 基于GTID的主从复制(实操)
  10. Unix系统使用的地址索引结构有什么特点?