代码写的不是很规范,大家可以拿过去直接改
功能:
上传,下载数据。支持进度显示。
多网络任务异步封装。
采用block处理。
所以需要5.0以上的系统。
具体使用示例:
第一个是第一次使用时候封装。
// // CWLWConnectManager.h // LechaoDrawGuess // // Created by luoge on 12-11-19. // Copyright (c) 2012年 watsy. All rights reserved. // #import <Foundation/Foundation.h> #import "ASIHTTPRequest.h" #import "ASIFormDataRequest.h" typedef enum { connectType_GET = 0, connectType_POST } connectType; @interface CWLWConnectManager : NSObject + (CWLWConnectManager *) sharedInstance; + (void) releaseInstance; //投递方法 - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params delegate:(id) del; - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params delegate:(id) del tag:(NSInteger) nTag; - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params delegate:(id) del tag:(NSInteger) nTag key:(NSString *) sKey; #if NS_BLOCKS_AVAILABLE - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params result:(void(^)(BOOL bSuccess,id returnData,NSError *error)) block; - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params tag:(NSInteger) nTag result:(void(^)(BOOL bSuccess,id returnData,NSError *error,NSInteger nTag)) block; - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params tag:(NSInteger) nTag key:(NSString *) sKey result:(void(^)(BOOL bSuccess,id returnData,NSError *error,NSInteger nTag, NSString *skey)) block; #endif //取消网络连接 - (BOOL) cancelWithHashValue:(NSUInteger) nItemHashValue; - (BOOL) cancelURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params delegate:(id) del tag:(NSInteger) nTag key:(NSString *) sKey; @end @interface NSObject(CWLCConnection) - (void) didCWFinishSuccessedWithData:(id) data tag:(NSInteger) nTag key:(NSString *) sKey; - (void) didCWFinishFailedWithError:(NSError *) error tag:(NSInteger) nTag key:(NSString *) sKey; @end
// // CWLWConnectManager.m // LechaoDrawGuess // // Created by luoge on 12-11-19. // Copyright (c) 2012年 watsy. All rights reserved. // #import "CWLWConnectManager.h" static CWLWConnectManager *_pConnectionMgr_ = nil; @interface CWConnItem : NSObject <ASIHTTPRequestDelegate> @property (nonatomic, assign) connectType cType; @property (nonatomic, assign) NSInteger nTag; @property (nonatomic, strong) NSString *sKey; @property (nonatomic, assign) id delegate; @property (nonatomic, strong) NSString *sURL; @property (nonatomic, strong) NSDictionary *params; @property (nonatomic, strong) ASIHTTPRequest *httpReq; + (CWConnItem *) connWithtype:(connectType) ct url:(NSString *) sl params:(NSDictionary *) pd Tag:(NSInteger) nt key:(NSString *) sk delegate:(id) del; - (CWConnItem *) initWithtype:(connectType) ct url:(NSString *) sl params:(NSDictionary *) pd Tag:(NSInteger) nt key:(NSString *) sk blockWithOutTagAndKey:(void(^)(BOOL bSuccess,id returnData,NSError *error)) blockWithOutTagAndKey blockWithOutKey:(void(^)(BOOL bSuccess,id returnData,NSError *error,NSInteger nTag)) blockWithOutKey block:(void(^)(BOOL bSuccess,id returnData,NSError *error,NSInteger nTag, NSString *skey)) block; - (void) start; @end @implementation CWConnItem @synthesize nTag,sKey,delegate,sURL,cType,params; @synthesize httpReq; - (void) dealloc { [httpReq clearDelegatesAndCancel]; [httpReq release]; [params release]; [sURL release]; [sKey release]; [super dealloc]; } + (CWConnItem *) connWithtype:(connectType) ct url:(NSString *) sl params:(NSDictionary *) pd Tag:(NSInteger) nt key:(NSString *) sk delegate:(id) del { CWConnItem *item = [[CWConnItem alloc] init]; item.nTag = nt; item.sKey = sk; item.sURL = sl; item.delegate = del; item.cType = ct; item.params = pd; return [item autorelease]; } - (CWConnItem *) initWithtype:(connectType) ct url:(NSString *) sl params:(NSDictionary *) pd Tag:(NSInteger) nt key:(NSString *) sk blockWithOutTagAndKey:(void(^)(BOOL bSuccess,id returnData,NSError *error)) blockWithOutTagAndKey blockWithOutKey:(void(^)(BOOL bSuccess,id returnData,NSError *error,NSInteger nTag)) blockWithOutKey block:(void(^)(BOOL bSuccess,id returnData,NSError *error,NSInteger nTag, NSString *skey)) block { if (self = [super init]) { self.nTag = nt; self.sKey = sk; self.sURL = sl; self.cType = ct; self.params = pd; if (cType == connectType_GET) { self.httpReq = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:sURL]]; [httpReq setRequestMethod:@"GET"]; } else if (cType == connectType_POST) { self.httpReq = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:sURL]]; [httpReq setRequestMethod:@"POST"]; ASIFormDataRequest *form = (ASIFormDataRequest *) httpReq; for (NSString *paramKey in [params allKeys]) { id paramValue = [params objectForKey:paramKey]; if ([paramValue isKindOfClass:[NSString class]]) { [form addPostValue:paramValue forKey:paramKey]; } else if ([paramValue isKindOfClass:[NSNumber class]]) { [form addPostValue:[paramValue stringValue] forKey:paramKey]; } } } [httpReq setCompletionBlock:^(void) { JSONDecoder *dec = [[JSONDecoder alloc] initWithParseOptions:JKParseOptionNone]; NSError *errParser = nil; id parObj = [dec objectWithData:httpReq.responseData error:&errParser]; //如果没有tag和key if (blockWithOutTagAndKey) { if (!errParser) { blockWithOutTagAndKey(YES, parObj, nil); } else { blockWithOutTagAndKey(NO, nil, errParser); } } //如果没有key if (blockWithOutKey) { if (!errParser) { blockWithOutKey(YES, parObj, nil, nTag); } else { blockWithOutKey(NO, nil, errParser, nTag); } } if (block) { if (!errParser) { block(YES, parObj, nil, self.nTag, self.sKey); } else { block(NO, nil, errParser, self.nTag, self.sKey); } } if([[CWLWConnectManager sharedInstance] respondsToSelector:@selector(didFinishedWithItems:error:)]) { [[CWLWConnectManager sharedInstance] performSelector:@selector(didFinishedWithItems:error:) withObject:self withObject:nil]; } [dec release]; }]; [httpReq setFailedBlock:^(void) { if (blockWithOutTagAndKey) { blockWithOutTagAndKey(NO, httpReq.responseString, httpReq.error); } if (blockWithOutKey) { blockWithOutKey(NO, httpReq.responseString, httpReq.error, nTag); } if (block) { block(NO, httpReq.responseString, httpReq.error, self.nTag, self.sKey); } if([[CWLWConnectManager sharedInstance] respondsToSelector:@selector(didFinishedWithItems:error:)]) { [[CWLWConnectManager sharedInstance] performSelector:@selector(didFinishedWithItems:error:) withObject:self withObject:httpReq.error]; } }]; [httpReq start]; } return self; } - (void) start { NSAssert((sURL != nil), @"url can't be nil"); sURL = [sURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; if (cType == connectType_GET) { httpReq = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:sURL]]; [httpReq setRequestMethod:@"GET"]; } else if (cType == connectType_POST) { httpReq = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:sURL]]; [httpReq setRequestMethod:@"POST"]; ASIFormDataRequest *form = (ASIFormDataRequest *) httpReq; for (NSString *paramKey in [params allKeys]) { [form addPostValue:[params objectForKey:paramKey] forKey:paramKey]; } } httpReq.delegate = self; [httpReq startAsynchronous]; } - (BOOL) isEqual:(id)object { CWConnItem *item = (CWConnItem *)object; if (![self.sURL isEqualToString:item.sURL]) { return NO; } if (self.cType != item.cType) { return NO; } if (self.delegate != item.delegate) { return NO; } if (self.nTag != item.nTag) { return NO; } if (self.sKey != nil && item.sKey != nil && ![self.sKey isEqualToString:item.sKey]) { return NO; } for (NSString *paramKey in self.params) { id sp1 = [self.params objectForKey:paramKey]; id sp2 = [self.params objectForKey:paramKey]; if (sp2 == nil) { return NO; } if (![sp1 isEqual:sp2]) { return NO; } } return YES; } - (void)requestFinished:(ASIHTTPRequest *)request { if([[CWLWConnectManager sharedInstance] respondsToSelector:@selector(didFinishedWithItems:error:)]) { [[CWLWConnectManager sharedInstance] performSelector:@selector(didFinishedWithItems:error:) withObject:self withObject:nil]; } } - (void)requestFailed:(ASIHTTPRequest *)request { if([[CWLWConnectManager sharedInstance] respondsToSelector:@selector(didFinishedWithItems:error:)]) { [[CWLWConnectManager sharedInstance] performSelector:@selector(didFinishedWithItems:error:) withObject:self withObject:request.error]; } } @end #pragma mark - CWLWConnectManager @interface CWLWConnectManager() @property (nonatomic, strong) NSMutableDictionary *connItems; //移除元素 - (id) hasItem:(CWConnItem *) item; - (void) removeItems:(CWConnItem *) conn; - (void) didFinishedWithItems:(CWConnItem *) conn error:(NSError *) error; @end @implementation CWLWConnectManager @synthesize connItems; - (id) init { if (_pConnectionMgr_) { return _pConnectionMgr_; } if (self = [super init]) { self.connItems = [NSMutableDictionary dictionary]; } return self; } - (void) dealloc { [connItems release]; [super dealloc]; } + (CWLWConnectManager *) sharedInstance { if (_pConnectionMgr_ == nil) { _pConnectionMgr_ = [[CWLWConnectManager alloc] init]; } return _pConnectionMgr_; } + (void) releaseInstance { if (_pConnectionMgr_ != nil) { [_pConnectionMgr_ release]; _pConnectionMgr_ = nil; } } - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params delegate:(id) del { return [self conURL:sURL connectType:cType params:params delegate:del tag:0]; } - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params delegate:(id) del tag:(NSInteger) nTag { return [self conURL:sURL connectType:cType params:params delegate:del tag:nTag key:nil]; } - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params delegate:(id) del tag:(NSInteger) nTag key:(NSString *) sKey { CWConnItem *item = [CWConnItem connWithtype:cType url:sURL params:params Tag:nTag key:sKey delegate:del]; if ([self hasItem:item]) { //重复调用方法 } NSUInteger hashValue = [item hash]; [self.connItems setObject:item forKey:[NSNumber numberWithUnsignedInteger:hashValue]]; [item start]; return hashValue; } //取消网络连接 - (BOOL) cancelWithHashValue:(NSUInteger) nItemHashValue { CWConnItem *conn = [self.connItems objectForKey:[NSNumber numberWithUnsignedInteger:nItemHashValue]]; if (conn) { [conn.httpReq clearDelegatesAndCancel]; [self.connItems removeObjectForKey:[NSNumber numberWithUnsignedInteger:nItemHashValue]]; } return YES; } - (BOOL) cancelURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params delegate:(id) del tag:(NSInteger) nTag key:(NSString *) sKey { CWConnItem *item = [CWConnItem connWithtype:cType url:sURL params:params Tag:nTag key:sKey delegate:del]; CWConnItem *existItem = [self hasItem:item]; if (existItem != nil) { if (existItem.httpReq != nil) { [existItem.httpReq clearDelegatesAndCancel]; } [self.connItems removeObjectForKey:[NSNumber numberWithUnsignedInteger:[existItem hash]]]; return NO; } return YES; } - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params result:(void(^)(BOOL bSuccess,id returnData,NSError *error)) block { CWConnItem *item = [[CWConnItem alloc] initWithtype:cType url:sURL params:params Tag:0 key:nil blockWithOutTagAndKey:block blockWithOutKey:nil block:nil]; NSUInteger hashValue = [item hash]; [self.connItems setObject:item forKey:[NSNumber numberWithUnsignedInteger:hashValue]]; [item release]; return hashValue; } - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params tag:(NSInteger) nTag result:(void(^)(BOOL bSuccess,id returnData,NSError *error,NSInteger nTag)) block { CWConnItem *item = [[CWConnItem alloc] initWithtype:cType url:sURL params:params Tag:nTag key:nil blockWithOutTagAndKey:nil blockWithOutKey:block block:nil]; NSUInteger hashValue = [item hash]; [self.connItems setObject:item forKey:[NSNumber numberWithUnsignedInteger:hashValue]]; [item release]; return hashValue; } - (NSUInteger) conURL:(NSString *) sURL connectType:(connectType) cType params:(NSDictionary *) params tag:(NSInteger) nTag key:(NSString *) sKey result:(void(^)(BOOL bSuccess,id returnData,NSError *error,NSInteger nTag, NSString *skey)) block { CWConnItem *item = [[CWConnItem alloc] initWithtype:cType url:sURL params:params Tag:nTag key:sKey blockWithOutTagAndKey:nil blockWithOutKey:nil block:block]; NSUInteger hashValue = [item hash]; [self.connItems setObject:item forKey:[NSNumber numberWithUnsignedInteger:hashValue]]; [item release]; return hashValue; } #pragma mark - private action - (id) hasItem:(CWConnItem *) conn { NSUInteger hashValue = [conn hash]; id object = [self.connItems objectForKey:[NSNumber numberWithUnsignedInteger:hashValue]]; if (object == nil) { for(id item in [self.connItems allValues]) { if ([conn isEqual:item]) { return item; } } } else { return conn; } return nil; } - (void) removeItems:(CWConnItem *) conn { NSUInteger hashValue = [conn hash]; id object = [self.connItems objectForKey:[NSNumber numberWithUnsignedInteger:hashValue]]; if (object != nil) { [[(CWConnItem *)object httpReq] clearDelegatesAndCancel]; [self.connItems removeObjectForKey:[NSNumber numberWithUnsignedInteger:hashValue]]; } } - (void) didFinishedWithItems:(CWConnItem *) conn error:(NSError *) error { if (error == nil) { if (conn.delegate && [conn.delegate respondsToSelector:@selector(didCWFinishSuccessedWithData:tag:key:)]) { [conn.delegate didCWFinishSuccessedWithData:conn.httpReq.responseString tag:conn.nTag key:conn.sKey]; } } else { if (conn.delegate && [conn.delegate respondsToSelector:@selector(didCWFinishFailedWithError:tag:key:)]) { [conn.delegate didCWFinishFailedWithError:error tag:conn.nTag key:conn.sKey]; } } [self removeItems:conn]; } @end
后来看到ASIHttpRequest类库脸红。从新封装了一下
// // CWConnQueue.h // ASIMultiQueue // // Created by 王 岩 on 13-1-17. // Copyright (c) 2013年 王 岩. All rights reserved. // #import <Foundation/Foundation.h> #import "ASINetworkQueue.h" //typedef enum //{ // connectType_GET = 0, // connectType_POST // //} connectType; typedef enum { recvDataType_Default = 0, recvDataType_Data, recvDataType_String, recvDataType_JSON, recvDataType_XML //暂不支持 } recvDataType; //typedef void (^cwCompletionBlock) (BOOL bSuccess, id returnData, NSError *error); typedef void (^cwCompletionBlockWithTag) (BOOL bSuccess, id returnData, NSError *error, NSInteger nTag); typedef void (^cwCompletionBlockWithTagAndKey) (BOOL bSuccess, id returnData, NSError *error, NSInteger nTag, NSString *sKey); @interface CWConnQueue : NSObject + (id) sharedInstance; + (void) releaseInstance; #if NS_BLOCKS_AVAILABLE - (void) connURL:(NSString *) sURL type:(connectType) cType params:(NSDictionary *) pDict progress:(id) progress recvType:(recvDataType) rType completion:(cwCompletionBlock) block; - (void) connURL:(NSString *) sURL type:(connectType) cType params:(NSDictionary *) pDict progress:(id) progress tag:(NSInteger) nTag recvType:(recvDataType) rType completion:(cwCompletionBlockWithTag) block; - (void) connURL:(NSString *) sURL type:(connectType) cType params:(NSDictionary *) pDict progress:(id) progress tag:(NSInteger) nTag key:(NSString *) sKey recvType:(recvDataType) rType completion:(cwCompletionBlockWithTagAndKey) block; #endif @end
// // CWConnQueue.m // ASIMultiQueue // // Created by 王 岩 on 13-1-17. // Copyright (c) 2013年 王 岩. All rights reserved. // #import "CWConnQueue.h" #import "ASIHTTPRequest.h" #import "ASIFormDataRequest.h" #import <Foundation/NSPointerArray.h> #import <Foundation/NSJSONSerialization.h> static CWConnQueue *_pConnQueue_ = nil; @interface CWConnQueue() - (void) queueDidFinish:(ASINetworkQueue *) sender; - (ASIHTTPRequest *) getHTTPReqWithURL:(NSURL *) url progress:(id) prog type:(connectType) cType param:(NSDictionary *) pDict; - (id) getHTTPReqRecvData:(ASIHTTPRequest *) req type:(recvDataType) rType error:(NSError **) error; @end @implementation CWConnQueue { @private ASINetworkQueue *_queue_; } + (id) sharedInstance { if (_pConnQueue_ == nil) { _pConnQueue_ = [[CWConnQueue alloc] init]; } return _pConnQueue_; } + (void) releaseInstance { if (_pConnQueue_ != nil) { [_pConnQueue_ release]; _pConnQueue_ = nil; } } - (id) init { if (self = [super init]) { _queue_ = [[ASINetworkQueue queue] retain]; [_queue_ setDelegate:self]; [_queue_ setQueueDidFinishSelector:@selector(queueDidFinish:)]; } return self; } - (void) dealloc { [_queue_ cancelAllOperations]; [_queue_ release]; [super dealloc]; } - (void) connURL:(NSString *) sURL type:(connectType) cType params:(NSDictionary *) pDict progress:(id) progress recvType:(recvDataType) rType completion:(cwCompletionBlock) block { NSURL *url = [NSURL URLWithString:[sURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]; NSAssert1(url != nil, @"url error at : %s", __FUNCTION__); ASIHTTPRequest *req = [self getHTTPReqWithURL:url progress:progress type:cType param:pDict]; [req setCompletionBlock:^ { NSError *error = nil; id rData = [self getHTTPReqRecvData:req type:rType error:&error]; if (error == nil) { block (YES, rData, nil); } else { block (NO, nil, error); } }]; if (progress) { [req setDownloadProgressDelegate:progress]; } [req setFailedBlock:^ { block(NO, nil, req.error); }]; [_queue_ addOperation:req]; [_queue_ go]; } - (void) connURL:(NSString *) sURL type:(connectType) cType params:(NSDictionary *) pDict progress:(id) progress tag:(NSInteger) nTag recvType:(recvDataType) rType completion:(cwCompletionBlockWithTag) block { NSURL *url = [NSURL URLWithString:[sURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]; NSAssert1(url != nil, @"url error at : %s", __FUNCTION__); ASIHTTPRequest *req = [self getHTTPReqWithURL:url progress:progress type:cType param:pDict]; [req setCompletionBlock:^ { NSError *error = nil; id rData = [self getHTTPReqRecvData:req type:rType error:&error]; if (error == nil) { block(YES, rData, nil, nTag); } else { block (NO, nil, error, nTag); } }]; if (progress) { [req setDownloadProgressDelegate:progress]; } [req setFailedBlock:^ { block(NO, nil, req.error, nTag); }]; [_queue_ addOperation:req]; [_queue_ go]; } - (void) connURL:(NSString *) sURL type:(connectType) cType params:(NSDictionary *) pDict progress:(id) progress tag:(NSInteger) nTag key:(NSString *) sKey recvType:(recvDataType) rType completion:(cwCompletionBlockWithTagAndKey) block { NSURL *url = [NSURL URLWithString:[sURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]; NSAssert1(url != nil, @"url error at : %s", __FUNCTION__); ASIHTTPRequest *req = [self getHTTPReqWithURL:url progress:progress type:cType param:pDict]; [req setCompletionBlock:^ { NSError *error = nil; id rData = [self getHTTPReqRecvData:req type:rType error:&error]; if (error == nil) { block(YES, rData, nil, nTag, sKey); } else { block(NO, nil, error, nTag, sKey); } }]; [req setFailedBlock:^ { block(NO, nil, req.error, nTag, sKey); }]; [_queue_ addOperation:req]; [_queue_ go]; } #pragma mark - private methods - (void) queueDidFinish:(ASINetworkQueue *)sender { } - (ASIHTTPRequest *) getHTTPReqWithURL:(NSURL *) url progress:(id) prog type:(connectType) cType param:(NSDictionary *) pDict { ASIHTTPRequest *req = nil; if (cType == connectType_GET) { req = [ASIHTTPRequest requestWithURL:url]; [req setRequestMethod:@"GET"]; } else if (cType == connectType_POST) { req = [ASIFormDataRequest requestWithURL:url]; [req setRequestMethod:@"POST"]; ASIFormDataRequest *form = (ASIFormDataRequest *) req; for (NSString *paramKey in [pDict allKeys]) { id paramValue = [pDict objectForKey:paramKey]; if ([paramValue isKindOfClass:[NSString class]]) { [form addPostValue:paramValue forKey:paramKey]; } else if ([paramValue isKindOfClass:[NSNumber class]]) { [form addPostValue:[paramValue stringValue] forKey:paramKey]; } } } if (prog) { [req setDownloadProgressDelegate:prog]; } return req; } - (id) getHTTPReqRecvData:(ASIHTTPRequest *) req type:(recvDataType) rType error:(NSError **) error { if (req.error != nil) { *error = req.error; return nil; } if (rType == recvDataType_Default || rType == recvDataType_String) { *error = nil; return req.responseString; } else if (rType == recvDataType_Data) { *error = nil; return req.responseData; } else if (rType == recvDataType_JSON) { NSError *jerr = nil; id jsonData = [NSJSONSerialization JSONObjectWithData:req.responseData options:NSJSONReadingMutableContainers error:&jerr]; if (jerr != nil) { *error = jerr; return jsonData; } else { *error = nil; return jsonData; } } else if (rType == recvDataType_XML) { #warning 以后增加上 xml支持 NSAssert(rType == recvDataType_Data, @"sorry, we will support XML soon"); } *error = nil; return nil; } @end