// // ASIDownManager.m // ManziDigest // // Created by Hepburn Alex on 12-9-19. // Copyright (c) 2012年 Hepburn Alex. All rights reserved. // #import "ASIDownManager.h" #import "ASIFormDataRequest.h" #import "LeslieImageCache.h" @interface ASIDownManager() { } @end @implementation ASIDownManager // NSOperationQueue static NSOperationQueue *queue; // 属性 @synthesize delegate, OnImageDown, OnImageFail, tag, mWebStr; /** 初始化矩阵 @return <#return value description#> */ - (id)init { self = [super init]; if (self) { if(queue){ queue=[[NSOperationQueue alloc]init]; } } return self; } /** 请求取消 */ - (void)Cancel { if (mRequest) { mRequest.delegate = nil; [mRequest clearDelegatesAndCancel]; [mRequest release]; mRequest = nil; } } /** dealloc */ - (void)dealloc { [self Cancel]; self.delegate = nil; self.mWebStr = nil; [super dealloc]; } /** 下载图片 @param imageUrl <#imageUrl description#> @return <#return value description#> */ - (NSString *)downloadImageWithURL:(NSString *)imageUrl { LeslieImageCache *imageCache = [LeslieImageCache sharedCache]; NSString * filePath; UIImage *image ; // image = [imageCache getImageFromMemoryForkey:imageUrl]; // // 先从内存中取 // if (image) { // return image; // } // 再从文件中取 filePath = [imageCache getImagePathFromFileForKey:imageUrl]; if (filePath) { return filePath; } image=[self SynchronousDownloadFromURL:imageUrl]; if (image) { // // 先缓存图片到内存 // [imageCache cacheImageToMemory:image forKey:imageUrl]; // 再缓存图片到文件系统 NSString *extension = [[imageUrl substringFromIndex:imageUrl.length-3] lowercaseString]; NSString *imageType = nil; if ([extension isEqualToString:@"jpg"]) { imageType =[@"jpg" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] ; }else{ imageType =[@"png" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] ; } filePath= [imageCache writeImageToFile:image forKey:imageUrl ofType:imageType]; return filePath; } return nil; } /** 开启同步请求 @param url <#url description#> @return <#return value description#> */ -(UIImage *)SynchronousDownloadFromURL:(NSString *)url { url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; NSURLRequest * urlReq = [NSURLRequest requestWithURL: [NSURL URLWithString: url]]; NSError* error=nil; //开启同步请求 NSData* data=[NSURLConnection sendSynchronousRequest:urlReq returningResponse:nil error:&error]; //[mRequest startSynchronous]; if(error || !data){ return nil; } return [[UIImage alloc] initWithData:data]; } /** 开启异步请求 @param urlString <#urlString description#> @param dict <#dict description#> @param filePath <#filePath description#> @param filename <#filename description#> @param fileType <#fileType description#> @return <#return value description#> */ - (NSString *)syncPostHttpRequestUrl:(NSString *)urlString dic:(NSDictionary *)dict path:(NSString *)filePath filename:(NSString *)filename fileType:(NSString *)fileType { NSURL *url = [NSURL URLWithString:urlString]; NSString *responseString=nil; mRequest = [[ASIFormDataRequest alloc] initWithURL:url]; // 参数 [mRequest setTimeOutSeconds:120]; mRequest.useCookiePersistence=YES; for (NSString *key in dict.allKeys) { NSString *value = [dict objectForKey:key]; [mRequest addPostValue:value forKey:key]; } //文件存在 if(filePath){ if(filename){ [mRequest setFile:filePath withFileName:filename andContentType:fileType forKey:filename]; }else{ [mRequest setFile:filePath withFileName:filename andContentType:fileType forKey:@"files"]; } } [mRequest startSynchronous]; NSError* error=[mRequest error]; if(error || [mRequest responseStatusCode] != 200){ responseString=@""; NSLog(@"requestFailed %@",responseString); return responseString; } NSData *data = [mRequest responseData]; responseString= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return responseString; } /** 开启异步请求 @param urlString <#urlString description#> @param dict <#dict description#> @param filepath filepath description @param filename filename description */ - (void) postHttpRequest:(NSString *)urlString dic:(NSDictionary *)dict path:(NSString *)filepath fileName:(NSString *)filename { NSURL *url = [NSURL URLWithString:urlString]; mRequest = [[ASIFormDataRequest alloc] initWithURL:url]; [mRequest setTimeOutSeconds:120]; for (NSString *key in dict.allKeys) { NSString *value = [dict objectForKey:key]; [mRequest addPostValue:value forKey:key]; } if (filepath) { [mRequest addFile:filepath forKey:filename]; } /* if(kkSessionID!=nil&&![kkSessionID isEqualToString:@""]) { [mRequest addRequestHeader:@"Cookie" value:kkSessionID]; }*/ mRequest.useCookiePersistence=YES; [mRequest setDelegate:self]; [queue addOperation:mRequest]; [mRequest startAsynchronous]; // [mRequest release]; } /** post异步请求 @param urlString <#urlString description#> @param dict <#dict description#> @param files <#files description#> */ - (void)postHttpRequest:(NSString *)urlString dic:(NSDictionary *)dict files:(NSDictionary *)files { NSLog(@"PostHttpRequest:%@, %@, %@", urlString, dict, files); NSURL *url = [NSURL URLWithString:urlString]; mRequest = [[ASIFormDataRequest alloc] initWithURL:url]; [mRequest setTimeOutSeconds:120]; /* 如果设置useCookiePersistence为YES(默认值),cookie会被存储在共享的 NSHTTPCookieStorage 容器中,并且会自动被其他request重用。值得一提的是,ASIHTTPRequest会向服务器发送其他程序创建的cookie(如果这些cookie对特定request有效的话)。 */ //记住用户状态的sessionid mRequest.useCookiePersistence=YES; for (NSString *key in dict.allKeys) { NSString *value = [dict objectForKey:key]; [mRequest addPostValue:value forKey:key]; } for (NSString *key in files.allKeys) { NSString *value = [files objectForKey:key]; [mRequest addFile:value forKey:key]; } // if(kkSessionID!=nil&&![kkSessionID isEqualToString:@""]) // { //[mRequest addPostValue:SessionId forKey:@"cookie"]; // [mRequest addRequestHeader:@"Cookie" value:kkSessionID]; /* NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease]; [properties setValue:@"/asi-http-request/tests" forKey:NSHTTPCookiePath]; NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease]; url = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"]; request = [ASIHTTPRequest requestWithURL:url]; [request setUseCookiePersistence:NO]; [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]]; [request startSynchronous];*/ // } [mRequest setDelegate:self]; [queue addOperation:mRequest]; [mRequest startAsynchronous]; } /** 请求完成函数 @param _request <#_request description#> */ - (void)requestFinished:(ASIHTTPRequest *)_request { // NSArray *arr=[_request responseCookies]; // NSDictionary *header=[_request responseHeaders]; // NSDictionary *dicheader=[NSDictionary dictionaryWithContentsOfData:header]; // ASP.NET_SessionId=31w2gp2by5lxhg2g1pzdmx45; path=/; HttpOnly /* if(kkSessionID==nil||[kkSessionID isEqualToString:@""]){ kkSessionID=[header objectForKey: @"Set-Cookie"]; } NSArray * array= [kkSessionID componentsSeparatedByString:@";"]; kkSessionID=array[0];*/ NSData *data = [_request responseData]; NSString *responseStr = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; [self Cancel]; if ([_request responseStatusCode] != 200) { NSLog(@"requestFinished Invalid:%d,%@", [_request responseStatusCode], _request.responseStatusMessage); if (delegate && OnImageFail) { [delegate performSelector:OnImageFail withObject:self]; } return; } responseStr = [responseStr stringByReplacingOccurrencesOfString:@"\r" withString:@""]; responseStr = [responseStr stringByReplacingOccurrencesOfString:@"\n" withString:@""]; self.mWebStr = responseStr; if (delegate && OnImageDown) { [delegate performSelector:OnImageDown withObject:self]; } } /** 请求失败函数 @param _request <#_request description#> */ - (void)requestFailed:(ASIHTTPRequest *)_request { NSData *data = [_request responseData]; NSString *responseStr = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; NSLog(@"requestFailed %@", responseStr); [self Cancel]; if (delegate && OnImageFail) { [delegate performSelector:OnImageFail withObject:self]; } } /** 动画开始 */ + (void)ShowNetworkAnimate { #if TARGET_OS_IPHONE [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; #endif } /** 动画结束 */ + (void)HideNetworkAnimate { #if TARGET_OS_IPHONE [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; #endif } @end