缘起
今天用暴风影音看视频,然后发现它有个功能,wifi传片,感觉挺有意思,然后就上网查了下相关内容。
原理
使用CocoaHTTPServer框架,在iOS端建立一个本地服务器,只要电脑和手机连入同一热点或者说网络,就可以实现通过电脑浏览器访问iOS服务器的页面,利用POST实现文件的上传。
实现
1.下载CocoaHTTPServer
2.导入CocoaHTTPServer-master
目录下的Core文件夹
3.导入Samples/SimpleFileUploadServer
目录下的MyHTTPConnection
类文件和web
文件夹
导入web文件夹的时候,一定要使用真实的目录,而不是xcode的虚拟目录
4.导入Vendor
目录下的CocoaAsyncSocket
、CocoaLumberjack
文件夹
5.打开MyHTTPConnection.m
文件,根据标记 #pragma mark multipart form data parser delegate 跳转或者直接找到139行的 *- (void) processStartOfPartWithHeader:(MultipartMessageHeader ) header 方法,把第151行的uploadDirPath
改为
NSString *uploadDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
这个路径是上传文件的存储路径
6.在适当的地方配置server启动。这里以AppDelegate为例
#import "AppDelegate.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import "HTTPServer.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import "MyHTTPConnection.h"
@interface AppDelegate ()
@property (nonatomic, strong) HTTPServer * httpServer;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_httpServer = [[HTTPServer alloc] init];
[_httpServer setPort:1234];
[_httpServer setType:@"_http._tcp."];
// webPath是server搜寻HTML等文件的路径
NSString * webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"web"];
[_httpServer setDocumentRoot:webPath];
[_httpServer setConnectionClass:[MyHTTPConnection class]];
NSError *err;
if ([_httpServer start:&err]) {
NSLog(@"port %hu",[_httpServer listeningPort]);
}else{
NSLog(@"%@",err);
}
NSString *ipStr = [self getIpAddresses];
NSLog(@"ip地址 %@", ipStr);
return YES;
}
- (NSString *)getIpAddresses{
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0)
{
// Loop through linked list of interfaces
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;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}
7.运行后,控制台会打印出端口号和ip,在电脑端浏览器里输入ip+端口号访问即可,如果成功的话会看到如下界面:
8.如果上传成功,网页上会出现上传的文件名,可以在沙盒里验证文件是否上传成功