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

Posted by Calvin on 2017-05-05

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

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

效果图1
「多看」和「掌阅」的 WiFi 传书页面

先看下最后的实现结果:

效果图1

进入 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 来传输文件,传输成功后点击关闭按钮,再次读取本地数据,可以查看到通过浏览器传输到手机的文件列表。

小结

  1. 「多看」和「掌阅」的端口号每次时唯一的,Demo 中的端口号是随机生成。
  2. 在文件传输时,需要浏览器和手机网络在同一局域网内。
  3. 文件传输时浏览器打开的 html 文件在 Demo 中,可以根据实际的需求进行页面的美化。
  4. 「多看」在文件传输中显示了文件传输的进度,这一点还没有研究好怎么实现。
  5. 文章 Demo 地址

参考资料

CocoaHTTPServer框架和Demo地址

利用CocoaHTTPServer实现wifi局域网传输文件到iphone