缘起
今天用暴风影音看视频,然后发现它有个功能,wifi传片,感觉挺有意思,然后就上网查了下相关内容。
原理
使用CocoaHTTPServer框架,在iOS端建立一个本地服务器,只要电脑和手机连入同一热点或者说网络,就可以实现通过电脑浏览器访问iOS服务器的页面,利用POST实现文件的上传。
实现
1.下载CocoaHTTPServer
2.导入CocoaHTTPServer-master目录下的Core文件夹
3.导入Samples/SimpleFileUploadServer目录下的MyHTTPConnection类文件和web文件夹
4.导入Vendor目录下的CocoaAsyncSocket、CocoaLumberjack文件夹
5.打开MyHTTPConnection.m文件,根据标记 #pragma mark multipart form data parser delegate 跳转或者直接找到139行的 *- (void) processStartOfPartWithHeader:(MultipartMessageHeader ) header 方法,把第151行的uploadDirPath改为
1
|
NSString *uploadDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
|
这个路径是上传文件的存储路径
6.在适当的地方配置server启动。这里以AppDelegate为例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
#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.如果上传成功,网页上会出现上传的文件名,可以在沙盒里验证文件是否上传成功
以上就是IOS利用CocoaHttpServer搭建手机本地服务器的详细内容,更多关于IOS用CocoaHttpServer搭建服务器的资料请关注服务器之家其它相关文章!
原文链接:https://juejin.cn/post/6953430592356614180