你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS技巧綜合 >> iOS 實現簡單的Http 服務

iOS 實現簡單的Http 服務

編輯:IOS技巧綜合
[摘要]本文是對iOS 實現簡單的Http 服務的講解,對學習IOS蘋果軟件開發有所幫助,與大家分享。

http 是計算機之間通訊協議的比較簡單的一種。在iPhone上,由於沒有同步數據和文件共享,所以實現PC與設備之間的數據傳輸的最佳方式就是在程序中嵌套一個http 服務器。在這篇帖子中,我將簡單的演示第三方的http 服務器的使用。

示例程序運行如下(在PC端輸入設備的IP和端口,便可選取當前PC的文件進行上傳至當前的設備)

該服務器涉及的相關類如下圖所示

代碼實現,創建一個自己需求的HttpConnection類繼承於第三方的HttpConnection,代碼如下

MyHTTPConnection.h

#import "HTTPConnection.h"

@class MultipartFormDataParser;

@interface MyHTTPConnection : HTTPConnection

{

MultipartFormDataParser * parser;

NSFileHandle * storeFile;

NSMutableArray * uploadedFiles;

}

@end

MyHTTPConnection.m

#import "MyHTTPConnection.h"

#import "HTTPMessage.h"

#import "HTTPDataResponse.h"

#import "DDNumber.h"

#import "HTTPLogging.h"

#import "MultipartFormDataParser.h"

#import "MultipartMessageHeaderField.h"

#import "HTTPDynamicFileResponse.h"

#import "HTTPFileResponse.h"

static const int httpLogLevel = HTTP_LOG_LEVEL_VERBOSE;

@interface MyHTTPConnection ()

{

float totalSize;

float progress;

}

@end

@implementation MyHTTPConnection

個人需要,1-8的方法都有實現

1:- (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path

{

NSLog(@"%s",__FUNCTION__);

HTTPLogTrace();

if ( [ method isEqualToString:@"POST"] ) {

if ( [path isEqualToString:@"/upload.html"] ) {

return YES;

}

}

return [super supportsMethod:method atPath:path];

}

2:-(BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path{

if([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.html"]) {

// here we need to make sure, boundary is set in header

NSString* contentType = [request headerField:@"Content-Type"];

NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;

if( NSNotFound == paramsSeparator ) {

return NO;

}

if( paramsSeparator >= contentType.length - 1 ) {

return NO;

}

NSString* type = [contentType substringToIndex:paramsSeparator];

if( ![type isEqualToString:@"multipart/form-data"] ) {

// we expect multipart/form-data content type

return NO;

}

// enumerate all params in content-type, and find boundary there

NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];

for( NSString* param in params ) {

paramsSeparator = [param rangeOfString:@"="].location;

if( (NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1 ) {

continue;

}

NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];

NSString* paramValue = [param substringFromIndex:paramsSeparator+1];

if( [paramName isEqualToString: @"boundary"] ) {

// let's separate the boundary from content-type, to make it more handy to handle

[request setHeaderField:@"boundary" value:paramValue];

}

}

// check if boundary specified

if( nil == [request headerField:@"boundary"] ) {

return NO;

}

return YES;

}

return [super expectsRequestBodyFromMethod:method atPath:path];

}

3:- (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path{

if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.html"])

{

// this method will generate response with links to uploaded file

NSMutableString* filesStr = [[NSMutableString alloc] init];

for( NSString* filePath in uploadedFiles ) {

//generate links

[filesStr appendFormat:@"%@<br/><br/>", [filePath lastPathComponent]];

}

NSString* templatePath = [[config documentRoot] stringByAppendingPathComponent:@"upload.html"];

NSDictionary* replacementDict = [NSDictionary dictionaryWithObject:filesStr forKey:@"MyFiles"];

// use dynamic file response to apply our links to response template

return [[HTTPDynamicFileResponse alloc] initWithFilePath:templatePath forConnection:self separator:@"%" replacementDictionary:replacementDict];

}

if( [method isEqualToString:@"GET"] && [path hasPrefix:@"/upload/"] ) {

// let download the uploaded files

return [[HTTPFileResponse alloc] initWithFilePath: [[config documentRoot] stringByAppendingString:path] forConnection:self];

}

return [super httpResponseForMethod:method URI:path];

}

4:- (void)prepareForBodyWithSize:(UInt64)contentLength{

HTTPLogTrace();

totalSize = contentLength/1000.0/1000.0;

NSLog(@"%f",contentLength/1000.0/1000.0);

// set up mime parser

NSString* boundary = [request headerField:@"boundary"];

parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];

parser.delegate = self;

uploadedFiles = [[NSMutableArray alloc] init];

}

5:- (void)processBodyData:(NSData *)postDataChunk{

HTTPLogTrace();

progress += postDataChunk.length/1024.0/1024.0;

NSLog(@"%f",progress);

NSString * temp = [ NSString stringWithFormat:@"上傳進度:%.2fMB/%.2fMB",progress,totalSize ];

dispatch_async(dispatch_get_main_queue(), ^{

[SVProgressHUD showProgress:progress/totalSize status:temp maskType:SVProgressHUDMaskTypeBlack];

});

// append data to the parser. It will invoke callbacks to let us handle

// parsed data.

[parser appendData:postDataChunk];

}

6:- (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header{

NSLog(@"%s",__FUNCTION__);

MultipartMessageHeaderField* disposition = [header.fields objectForKey:@"Content-Disposition"];

NSString* filename = [[disposition.params objectForKey:@"filename"] lastPathComponent];

NSLog(@"####filename=%@",filename);

if ( (nil == filename) || [filename isEqualToString: @""] ) {

// it's either not a file part, or

// an empty form sent. we won't handle it.

return;

}

NSString* uploadDirPath = [self CreatreTempDir] ;

// NSLog(@"uploadDirPath%@",[self CreatDir]);

BOOL isDir = YES;

if (![[NSFileManager defaultManager]fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {

[[NSFileManager defaultManager]createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];

}

NSString * filePath = [uploadDirPath stringByAppendingPathComponent:filename];

NSFileManager * fileManager = [NSFileManager defaultManager];

if( [[NSFileManager defaultManager] fileExistsAtPath:filePath] ) {

storeFile = nil;

}

else {

HTTPLogVerbose(@"Saving file to %@", filePath);

NSError *error;

if(![[NSFileManager defaultManager] createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:&error]) {

HTTPLogError(@"Could not create directory at path: %@----%@", filePath,error);

}

if(![[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]) {

HTTPLogError(@"Could not create file at path: %@", filePath);

}

storeFile = [NSFileHandle fileHandleForWritingAtPath:filePath];

[uploadedFiles addObject: [NSString stringWithFormat:@"/upload/%@", filename]];

}

}

7:- (void) processContent:(NSData*) data WithHeader:(MultipartMessageHeader*) header{

if(!storeFile)

{

MultipartMessageHeaderField* disposition = [header.fields objectForKey:@"Content-Disposition"];

NSString* filename = [[disposition.params objectForKey:@"filename"] lastPathComponent];

NSLog(@"####filename=%@",filename);

if ( (nil == filename) || [filename isEqualToString: @""] ) {

// it's either not a file part, or

// an empty form sent. we won't handle it.

return;

}

NSString* uploadDirPath = [self CreatreTempDir] ;

NSString * filePath = [uploadDirPath stringByAppendingPathComponent:filename];

storeFile = [NSFileHandle fileHandleForWritingAtPath:filePath];

[uploadedFiles addObject: [NSString stringWithFormat:@"/upload/%@", filename]];

}

if( storeFile ) {

[storeFile writeData:data];

}

}

8:- (void) processEndOfPartWithHeader:(MultipartMessageHeader*) header{

dispatch_async(dispatch_get_main_queue(), ^{

[SVProgressHUD dismiss];

});

progress = 0.f;

MultipartMessageHeaderField* disposition = [header.fields objectForKey:@"Content-Disposition"];

NSString* filename = [[disposition.params objectForKey:@"filename"] lastPathComponent] ;

// NSLog(@"####END ---filename=%@",filename);

NSString * tempFilePath = [[ self CreatreTempDir ] stringByAppendingPathComponent:filename];

NSMutableArray *arraynumber = [NSMutableArray arrayWithContentsOfFile:[Global getChangePathName]];

NSString *strnumber = [arraynumber lastObject];

NSString * uploadFilePath = [[ self CreatDir ] stringByAppendingPathComponent: [[NSString stringWithFormat:@"%d.",[strnumber intValue] + 1 ] stringByAppendingString:filename]];

[arraynumber addObject:[NSString stringWithFormat:@"%d", [strnumber intValue] + 1]];

[arraynumber writeToFile:[Global getChangePathName] atomically:YES];

BOOL result = [ self copyMissFile:tempFilePath toPath:uploadFilePath ];

if (result) {

NSLog(@"移動成功");

}else{

NSLog(@"移動失敗");

}

[storeFile closeFile];

storeFile = nil;

}

- (BOOL)copyMissFile:(NSString * )sourcePath toPath:(NSString *)toPath{

BOOL retVal ;

NSLog(@"%s",__FUNCTION__);

// if ( [fileManger fileExistsAtPath:toPath] ) {

// [fileManger removeItemAtPath:toPath error:nil];

// }

retVal = [[ NSFileManager defaultManager ] moveItemAtPath:sourcePath toPath:toPath error:nil];

return retVal;

}

下面兩個方法都是創建文件,大家自己可以隨意定義

-(NSString *)CreatDir;

-(NSString *)CreatreTempDir;

下面根據需求實現以下這些方法,我是在全局的類裡面實現的

Global.m

+ (BOOL)createiPhoneServer //創建並設置iPhone的服務器

{

Global * global = [ Global sharedGlobal ];

global.httpServer = [[HTTPServer alloc] init];

[global.httpServer setType:@"_http._tcp."];

NSString *docRoot = [[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MyResources"] stringByAppendingPathComponent:@"Web"];

BOOL isDir = YES ;

if ( [[NSFileManager defaultManager] fileExistsAtPath:docRoot isDirectory:&isDir ] ) {

NSLog(@"找到Web文件夾");

}

[global.httpServer setDocumentRoot:docRoot];

[global.httpServer setPort:Http_Port];//本地端口

[global.httpServer setConnectionClass:[MyHTTPConnection class]];//設置連接類為我們之前代碼實現的連接類

return YES;

}

//開啟服務器

+ (BOOL)startServer

{

Global * global = [ Global sharedGlobal];

NSError * error;

if ( [global.httpServer start:&error] ) {

NSLog(@"開啟成功%u",[global.httpServer listeningPort]);

return YES;

}else

{

NSLog(@"開啟失敗,%@",error);

return NO;

}

}

+ (BOOL)stopServer

{

[[Global sharedGlobal].httpServer stop:YES];

return YES;

}

//獲得當前設備的IP

+(NSString *)getIPAddress

{

NSString *address = @"開啟失敗";

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);

NSString * str = nil;

if ( [address isEqualToString:@"開啟失敗"] ) {

str = @"開啟失敗";

}else {

str = [NSString stringWithFormat:@"http://%@:%d",address, Http_Port ];

}

return str;

}

//獲取當前設備的網絡狀態

+(NSString *) getDeviceSSID

{

NSArray *ifs = (__bridge id)CNCopySupportedInterfaces() ;

id info = nil;

for (NSString *ifnam in ifs) {

info = (__bridge id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);

if (info && [info count]) {

break;

}

}

NSDictionary *dctySSID = (NSDictionary *)info;

NSString *ssid = [ dctySSID objectForKey:@"SSID" ];

ssid = ssid== nil?@"無網絡":ssid;

return ssid;

}

然後再你需要的地方開啟這個服務即可,至此http 服務搭建完成,開啟服務之後就可在PC的浏覽器輸入當前的設備IP地址和端口,如http://192.168.2.155:8088,然後上傳所需的文件即可,根據程序設計,這些文件會存在相應的地方

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved