ASIDownManager.m 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. //
  2. // ASIDownManager.m
  3. // ManziDigest
  4. //
  5. // Created by Hepburn Alex on 12-9-19.
  6. // Copyright (c) 2012年 Hepburn Alex. All rights reserved.
  7. //
  8. #import "ASIDownManager.h"
  9. #import "ASIFormDataRequest.h"
  10. #import "LeslieImageCache.h"
  11. @interface ASIDownManager()
  12. {
  13. }
  14. @end
  15. @implementation ASIDownManager
  16. // NSOperationQueue
  17. static NSOperationQueue *queue;
  18. // 属性
  19. @synthesize delegate, OnImageDown, OnImageFail, tag, mWebStr;
  20. /**
  21. 初始化矩阵
  22. @return <#return value description#>
  23. */
  24. - (id)init {
  25. self = [super init];
  26. if (self) {
  27. if(queue){
  28. queue=[[NSOperationQueue alloc]init];
  29. }
  30. }
  31. return self;
  32. }
  33. /**
  34. 请求取消
  35. */
  36. - (void)Cancel {
  37. if (mRequest) {
  38. mRequest.delegate = nil;
  39. [mRequest clearDelegatesAndCancel];
  40. [mRequest release];
  41. mRequest = nil;
  42. }
  43. }
  44. /**
  45. dealloc
  46. */
  47. - (void)dealloc {
  48. [self Cancel];
  49. self.delegate = nil;
  50. self.mWebStr = nil;
  51. [super dealloc];
  52. }
  53. /**
  54. 下载图片
  55. @param imageUrl <#imageUrl description#>
  56. @return <#return value description#>
  57. */
  58. - (NSString *)downloadImageWithURL:(NSString *)imageUrl {
  59. LeslieImageCache *imageCache = [LeslieImageCache sharedCache];
  60. NSString * filePath;
  61. UIImage *image ;
  62. // image = [imageCache getImageFromMemoryForkey:imageUrl];
  63. // // 先从内存中取
  64. // if (image) {
  65. // return image;
  66. // }
  67. // 再从文件中取
  68. filePath = [imageCache getImagePathFromFileForKey:imageUrl];
  69. if (filePath) {
  70. return filePath;
  71. }
  72. image=[self SynchronousDownloadFromURL:imageUrl];
  73. if (image) {
  74. // // 先缓存图片到内存
  75. // [imageCache cacheImageToMemory:image forKey:imageUrl];
  76. // 再缓存图片到文件系统
  77. NSString *extension = [[imageUrl substringFromIndex:imageUrl.length-3] lowercaseString];
  78. NSString *imageType = nil;
  79. if ([extension isEqualToString:@"jpg"]) {
  80. imageType =[@"jpg" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] ;
  81. }else{
  82. imageType =[@"png" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] ;
  83. }
  84. filePath= [imageCache writeImageToFile:image forKey:imageUrl ofType:imageType];
  85. return filePath;
  86. }
  87. return nil;
  88. }
  89. /**
  90. 开启同步请求
  91. @param url <#url description#>
  92. @return <#return value description#>
  93. */
  94. -(UIImage *)SynchronousDownloadFromURL:(NSString *)url
  95. {
  96. url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  97. NSURLRequest * urlReq = [NSURLRequest requestWithURL: [NSURL URLWithString: url]];
  98. NSError* error=nil;
  99. //开启同步请求
  100. NSData* data=[NSURLConnection sendSynchronousRequest:urlReq returningResponse:nil error:&error];
  101. //[mRequest startSynchronous];
  102. if(error || !data){
  103. return nil;
  104. }
  105. return [[UIImage alloc] initWithData:data];
  106. }
  107. /**
  108. 开启异步请求
  109. @param urlString <#urlString description#>
  110. @param dict <#dict description#>
  111. @param filePath <#filePath description#>
  112. @param filename <#filename description#>
  113. @param fileType <#fileType description#>
  114. @return <#return value description#>
  115. */
  116. - (NSString *)syncPostHttpRequestUrl:(NSString *)urlString
  117. dic:(NSDictionary *)dict
  118. path:(NSString *)filePath
  119. filename:(NSString *)filename
  120. fileType:(NSString *)fileType
  121. {
  122. NSURL *url = [NSURL URLWithString:urlString];
  123. NSString *responseString=nil;
  124. mRequest = [[ASIFormDataRequest alloc] initWithURL:url];
  125. // 参数
  126. [mRequest setTimeOutSeconds:120];
  127. mRequest.useCookiePersistence=YES;
  128. for (NSString *key in dict.allKeys) {
  129. NSString *value = [dict objectForKey:key];
  130. [mRequest addPostValue:value forKey:key];
  131. }
  132. //文件存在
  133. if(filePath){
  134. if(filename){
  135. [mRequest setFile:filePath withFileName:filename andContentType:fileType forKey:filename];
  136. }else{
  137. [mRequest setFile:filePath withFileName:filename andContentType:fileType forKey:@"files"];
  138. }
  139. }
  140. [mRequest startSynchronous];
  141. NSError* error=[mRequest error];
  142. if(error || [mRequest responseStatusCode] != 200){
  143. responseString=@"";
  144. NSLog(@"requestFailed %@",responseString);
  145. return responseString;
  146. }
  147. NSData *data = [mRequest responseData];
  148. responseString= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  149. return responseString;
  150. }
  151. /**
  152. 开启异步请求
  153. @param urlString <#urlString description#>
  154. @param dict <#dict description#>
  155. @param filepath filepath description
  156. @param filename filename description
  157. */
  158. - (void) postHttpRequest:(NSString *)urlString
  159. dic:(NSDictionary *)dict
  160. path:(NSString *)filepath
  161. fileName:(NSString *)filename
  162. {
  163. NSURL *url = [NSURL URLWithString:urlString];
  164. mRequest = [[ASIFormDataRequest alloc] initWithURL:url];
  165. [mRequest setTimeOutSeconds:120];
  166. for (NSString *key in dict.allKeys) {
  167. NSString *value = [dict objectForKey:key];
  168. [mRequest addPostValue:value forKey:key];
  169. }
  170. if (filepath) {
  171. [mRequest addFile:filepath forKey:filename];
  172. }
  173. /* if(kkSessionID!=nil&&![kkSessionID isEqualToString:@""])
  174. {
  175. [mRequest addRequestHeader:@"Cookie" value:kkSessionID];
  176. }*/
  177. mRequest.useCookiePersistence=YES;
  178. [mRequest setDelegate:self];
  179. [queue addOperation:mRequest];
  180. [mRequest startAsynchronous];
  181. // [mRequest release];
  182. }
  183. /**
  184. post异步请求
  185. @param urlString <#urlString description#>
  186. @param dict <#dict description#>
  187. @param files <#files description#>
  188. */
  189. - (void)postHttpRequest:(NSString *)urlString
  190. dic:(NSDictionary *)dict
  191. files:(NSDictionary *)files
  192. {
  193. NSLog(@"PostHttpRequest:%@, %@, %@", urlString, dict, files);
  194. NSURL *url = [NSURL URLWithString:urlString];
  195. mRequest = [[ASIFormDataRequest alloc] initWithURL:url];
  196. [mRequest setTimeOutSeconds:120];
  197. /*
  198. 如果设置useCookiePersistence为YES(默认值),cookie会被存储在共享的 NSHTTPCookieStorage 容器中,并且会自动被其他request重用。值得一提的是,ASIHTTPRequest会向服务器发送其他程序创建的cookie(如果这些cookie对特定request有效的话)。
  199. */
  200. //记住用户状态的sessionid
  201. mRequest.useCookiePersistence=YES;
  202. for (NSString *key in dict.allKeys) {
  203. NSString *value = [dict objectForKey:key];
  204. [mRequest addPostValue:value forKey:key];
  205. }
  206. for (NSString *key in files.allKeys) {
  207. NSString *value = [files objectForKey:key];
  208. [mRequest addFile:value forKey:key];
  209. }
  210. // if(kkSessionID!=nil&&![kkSessionID isEqualToString:@""])
  211. // {
  212. //[mRequest addPostValue:SessionId forKey:@"cookie"];
  213. // [mRequest addRequestHeader:@"Cookie" value:kkSessionID];
  214. /* NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];
  215. [properties setValue:@"/asi-http-request/tests" forKey:NSHTTPCookiePath];
  216. NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease];
  217. url = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"];
  218. request = [ASIHTTPRequest requestWithURL:url];
  219. [request setUseCookiePersistence:NO];
  220. [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
  221. [request startSynchronous];*/
  222. // }
  223. [mRequest setDelegate:self];
  224. [queue addOperation:mRequest];
  225. [mRequest startAsynchronous];
  226. }
  227. /**
  228. 请求完成函数
  229. @param _request <#_request description#>
  230. */
  231. - (void)requestFinished:(ASIHTTPRequest *)_request {
  232. // NSArray *arr=[_request responseCookies];
  233. // NSDictionary *header=[_request responseHeaders];
  234. // NSDictionary *dicheader=[NSDictionary dictionaryWithContentsOfData:header];
  235. // ASP.NET_SessionId=31w2gp2by5lxhg2g1pzdmx45; path=/; HttpOnly
  236. /* if(kkSessionID==nil||[kkSessionID isEqualToString:@""]){
  237. kkSessionID=[header objectForKey: @"Set-Cookie"];
  238. }
  239. NSArray * array= [kkSessionID componentsSeparatedByString:@";"];
  240. kkSessionID=array[0];*/
  241. NSData *data = [_request responseData];
  242. NSString *responseStr = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
  243. [self Cancel];
  244. if ([_request responseStatusCode] != 200) {
  245. NSLog(@"requestFinished Invalid:%d,%@", [_request responseStatusCode], _request.responseStatusMessage);
  246. if (delegate && OnImageFail) {
  247. [delegate performSelector:OnImageFail withObject:self];
  248. }
  249. return;
  250. }
  251. responseStr = [responseStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
  252. responseStr = [responseStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  253. self.mWebStr = responseStr;
  254. if (delegate && OnImageDown) {
  255. [delegate performSelector:OnImageDown withObject:self];
  256. }
  257. }
  258. /**
  259. 请求失败函数
  260. @param _request <#_request description#>
  261. */
  262. - (void)requestFailed:(ASIHTTPRequest *)_request {
  263. NSData *data = [_request responseData];
  264. NSString *responseStr = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
  265. NSLog(@"requestFailed %@", responseStr);
  266. [self Cancel];
  267. if (delegate && OnImageFail) {
  268. [delegate performSelector:OnImageFail withObject:self];
  269. }
  270. }
  271. /**
  272. 动画开始
  273. */
  274. + (void)ShowNetworkAnimate
  275. {
  276. #if TARGET_OS_IPHONE
  277. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  278. #endif
  279. }
  280. /**
  281. 动画结束
  282. */
  283. + (void)HideNetworkAnimate
  284. {
  285. #if TARGET_OS_IPHONE
  286. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  287. #endif
  288. }
  289. @end