iOS 实现 WiFi 局域网传输文件到 App

我经常使用「多看」和「掌阅」App 看书,其中有一个共同的功能就是 WiFi 传书,根据 App 的提示在电脑浏览器打开指定的地址,传入文件就可以直接发送到手机上阅读了。

虽然这个功能需求不是很多,但是也对其进行了一下研究,使用 CocoaHTTPServer 框架对其进行实现。



多看」和「掌阅」的 WiFi 传书页面

先看下最后的实现结果:



进入 App 内展示传输数据,默认是没有传输任何文件的,当点击添加按钮在浏览器进行文件传输后,关闭弹框就会发现传入的 2 个文件了。

原理

CocoaHTTPServer 框架能够在 iOS 上建立起一个本地服务器,只要电脑和移动设备连入同一局域网,即可使用电脑访问 iOS 服务器的指定页面,利用 POST 实现文件的上传。

功能实现

导入 CocoaHTTPServer 框架

这里推荐大家使用 cocospods 进行集成,只需在 “Podfile” 填写以下代码:

 
     
pod 'CocoaHTTPServer'

如图所示,导入成功

20170505149397075130489.png

配置 HttpConnectManager 类

创建基于 HTTPConnection 的 MyHTTPConnection 类,用来管理 HttpConnection。

找到 - (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header 方法,修改传入文件的地址为 Document 文件夹

 
     
NSString *uploadDirPath = [ NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
创建 IPAdress 管理类

创建基于 NSObject 的 DHIPAdress 类,用于获取手机的 IP 地址:

DHIPAdress.h

 
     
/*!
* get device ip address
*/
+ ( NSString *)deviceIPAdress;

DHIPAdress.m

 
     
+ ( 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;
}
传输文件和读取文件

默认进入 App 读取本地 Document 文件夹内的文件,首次进入 App 没有任何数据展示。

点击添加按钮,弹出浏览器的 POST 地址,http://192.168.10.192:58818 端口号为每次随机生成。

浏览器访问 index.html 和 upload.html 来传输文件,传输成功后点击关闭按钮,再次读取本地数据,可以查看到通过浏览器传输到手机的文件列表。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值