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

背景

近日在做一个代码阅读器,其中涉及到代码文件的上传,之前看到过许多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
原文地址:https://www.cnblogs.com/aiwz/p/6154012.html