// // RemoteResponse.m // codeChallengeDemo // // Created by Scar on 14-8-21. // Copyright (c) 2014年 scar1900. All rights reserved. // #import "RemoteResponse.h" #import "AppDelegate.h" @implementation Remote(Response) //- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders { // // TPLOG(@"header %@ %@ %@ ", [responseHeaders objectForKey:@"Content-Length"], [responseHeaders objectForKey:@"Content-Type"], // [responseHeaders objectForKey:@"Server"]); //} -(void) jsonFinished: (ASIHTTPRequest *) request { @synchronized(self) { __weak id delegate = [[request userInfo] objectForKey:@"delegate"]; int actionTag = [[[request userInfo] objectForKey:@"actionTag"] intValue]; @try { NSString *responseString = [NSString stringWithFormat:@"%@", [request responseString]]; responseString = [self dealResponseStringBeforeChange:responseString]; NSData *preJsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding]; //解析返回的json报文 NSDictionary *resDic = [self toArrayOrNSDictionary:preJsonData]; if (!resDic) { TPLOG(@"返回数据为空!"); if ([delegate respondsToSelector:@selector(remoteResponsFailed:withMessage:resultCode:)]) { [delegate remoteResponsFailed:actionTag withMessage:@"服务器连接异常,请检查网络。" resultCode:@""]; } [self performSelector:@selector(stopWaitCursor:) withObject:request.userInfo]; request.userInfo = nil; return; } if ([resDic[@"resultCode"] intValue] != 1) { TPLOG(@"%@",resDic[@"resultMsg"]); NSString *url = [NSString stringWithFormat:@"%@",request.url]; if (![url isMatchedByRegex:@"getuuid"]) { if ([delegate respondsToSelector:@selector(remoteResponsFailed:withMessage:resultCode:)]) { [delegate remoteResponsFailed:actionTag withMessage:resDic[@"resultMsg"] resultCode:resDic[@"resultCode"]]; if ([resDic[@"resultCode"] intValue] == 4) { NSString *uuid = resDic[@"uuid"]; if (uuid && !isBlankString(uuid)) { [TPUserDefault instance].uuid = uuid; } } } return; } } if ([delegate respondsToSelector:@selector(remoteResponsSuccess:withResponsData:)]) { [delegate remoteResponsSuccess:actionTag withResponsData:resDic]; } } @catch (NSException * e) { [self performSelector:@selector(onError:userInfo:) withObject:[e reason] withObject:[request userInfo]]; } @finally { [self performSelector:@selector(stopWaitCursor:) withObject:request.userInfo]; request.userInfo = nil; } } } - (void)jsonFinishedWithBlock: (ASIHTTPRequest *) request { @synchronized(self) { @try { NSString *responseString = [NSString stringWithFormat:@"%@", [request responseString]]; responseString = [self dealResponseStringBeforeChange:responseString]; NSData *preJsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding]; //解析返回的json报文 NSDictionary *resDic = [self toArrayOrNSDictionary:preJsonData]; // int (^square)(int); void(^completeHandler)(BOOL success,NSString *message,id responseData); completeHandler = [[request userInfo] objectForKey:@"completeHandler"]; if (!resDic) { TPLOG(@"返回数据为空!"); if (completeHandler) { completeHandler(NO,@"服务器连接异常,请检查网络。",nil); completeHandler = nil; } [self performSelector:@selector(stopWaitCursor:) withObject:request.userInfo]; request.userInfo = nil; return; } if ([resDic[@"resultCode"] intValue] != 1) { TPLOG(@"%@",resDic[@"resultMsg"]); NSString *url = [NSString stringWithFormat:@"%@",request.url]; if (![url isMatchedByRegex:@"getuuid"]) { if (completeHandler) { completeHandler(NO,resDic[@"resultMsg"],resDic[@"resultCode"]); completeHandler = nil; if ([resDic[@"resultCode"] intValue] == 4) { NSString *uuid = resDic[@"uuid"]; if (uuid && !isBlankString(uuid)) { [TPUserDefault instance].uuid = uuid; } } } return; } } if (completeHandler) { completeHandler(YES,nil,resDic); completeHandler = nil; } } @catch (NSException * e) { [self performSelector:@selector(onError:userInfo:) withObject:[e reason] withObject:[request userInfo]]; } @finally { [self performSelector:@selector(stopWaitCursor:) withObject:request.userInfo]; request.userInfo = nil; } } } - (void)noneJsonFinishedWithBlock: (ASIHTTPRequest *) request { @synchronized(self) { @try { NSString *responseString = [NSString stringWithFormat:@"%@", [request responseString]]; void(^completeHandler)(BOOL success,NSString *message,id responseData); completeHandler = [[request userInfo] objectForKey:@"completeHandler"]; if ([responseString isMatchedByRegex:@"success"]) { if (completeHandler) { completeHandler(YES,nil,responseString); completeHandler = nil; } }else { if (completeHandler) { completeHandler(NO,nil,responseString); completeHandler = nil; } } } @catch (NSException * e) { [self performSelector:@selector(onError:userInfo:) withObject:[e reason] withObject:[request userInfo]]; } @finally { [self performSelector:@selector(stopWaitCursor:) withObject:request.userInfo]; request.userInfo = nil; } } } - (void)DownloadFinish:(ASIHTTPRequest *)request { @synchronized(self) { @try { id delegate = [[request userInfo] objectForKey:@"delegate"]; int commandTag = [[[request userInfo] objectForKey:@"actionTag"] intValue]; NSString* fileName = [[request userInfo] objectForKey:@"fileName"]; //通知已成功下载消息给相关代理 if ([delegate respondsToSelector:@selector(remoteResponsSuccess:withResponsData:)]) { [delegate remoteResponsSuccess:commandTag withResponsData:fileName]; } //停止等待光标 // [self performSelector:@selector(stopWaitCursor:) // withObject:[request userInfo]]; // request.userInfo = nil; } @catch (NSException * e) { [self performSelector:@selector(onError:userInfo:) withObject:[e reason] withObject:[request userInfo]]; } @finally { [self performSelector:@selector(stopWaitCursor:) withObject:request.userInfo]; request.userInfo = nil; } } } - (void)DownloadFinishWithBlock:(ASIHTTPRequest *)request { @synchronized(self) { @try { NSString* fileName = [[request userInfo] objectForKey:@"fileName"]; if (self.downloadFinishHanlder) { self.downloadFinishHanlder(YES,nil,fileName); self.downloadFinishHanlder = nil; } } @catch (NSException * e) { [self performSelector:@selector(onError:userInfo:) withObject:[e reason] withObject:[request userInfo]]; } @finally { request.userInfo = nil; } } } - (void)requestFailed:(ASIHTTPRequest*)request { @synchronized(self) { @try { NSError *error = [request error]; //通知错误消息 [self performSelector:@selector(onNsError:userInfo:) withObject:error withObject:[request userInfo]]; } @catch (NSException *e) { [self performSelector:@selector(onError:userInfo:) withObject:[e reason] withObject:[request userInfo]]; } @finally { [self performSelector:@selector(stopWaitCursor:) withObject:request.userInfo]; request.userInfo = nil; } } } - (void)offlineDownloadFinished:(ASIHTTPRequest*)request { TPLOG(@"requestFinished"); id delegate = [[request userInfo] objectForKey:@"delegate"]; int commandTag = [[[request userInfo] objectForKey:@"actionTag"] intValue]; NSString* fileName = [[request userInfo] objectForKey:@"fileName"]; //通知已成功下载消息给相关代理 if ([delegate respondsToSelector:@selector(remoteResponsSuccess:withResponsData:)]) { [delegate remoteResponsSuccess:commandTag withResponsData:fileName]; } } - (void)imageUpLoadFinished:(ASIHTTPRequest*)request { @synchronized(self) { @try { self.xmlFinishHandler = nil; __block void(^completeHandler)(BOOL success,NSString *message,id responseData); __weak typeof(self) Self = self; [self parseXMLData:[request responseData] comlete:^(BOOL success, id responseData) { completeHandler = [[request userInfo] objectForKey:@"completeHandler"]; NSDictionary *dic = responseData; if (dic.allKeys.count == 0) { TPLOG(@"返回数据为空!"); dispatch_async(dispatch_get_main_queue(), ^{ if (completeHandler) { completeHandler(NO,@"服务器连接异常,请检查网络。",nil); completeHandler = nil; } [Self performSelector:@selector(stopWaitCursor:) withObject:request.userInfo]; request.userInfo = nil; }); return; } dispatch_async(dispatch_get_main_queue(), ^{ if (completeHandler) { completeHandler(YES,nil,dic); completeHandler = nil; } [Self performSelector:@selector(stopWaitCursor:) withObject:request.userInfo]; request.userInfo = nil; }); }]; } @catch (NSException * e) { [self performSelector:@selector(onError:userInfo:) withObject:[e reason] withObject:[request userInfo]]; } @finally { [self performSelector:@selector(stopWaitCursor:) withObject:request.userInfo]; request.userInfo = nil; } } } - (void)xmlRequestFinished:(ASIHTTPRequest*)request { @synchronized(self) { @try { self.xmlFinishHandler = nil; __block void(^completeHandler)(BOOL success,NSString *message,id responseData); [self parseXMLData:[request responseData] comlete:^(BOOL success, id responseData) { completeHandler = [[request userInfo] objectForKey:@"completeHandler"]; if (success) { NSDictionary *dic = responseData; if (dic.allKeys.count == 0) { TPLOG(@"返回数据为空!"); dispatch_async(dispatch_get_main_queue(), ^{ if (completeHandler) { completeHandler(NO,@"服务器连接异常,请检查网络。",nil); completeHandler = nil; } request.userInfo = nil; }); return; } dispatch_async(dispatch_get_main_queue(), ^{ if (completeHandler) { completeHandler(YES,nil,dic); completeHandler = nil; } request.userInfo = nil; }); }else { if (completeHandler) { completeHandler(NO,nil,nil); completeHandler = nil; } request.userInfo = nil; } }]; } @catch (NSException * e) { [self performSelector:@selector(onError:userInfo:) withObject:[e reason] withObject:[request userInfo]]; } @finally { request.userInfo = nil; } } } - (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes { int commandTag = [[[request userInfo] objectForKey:@"actionTag"] intValue]; NSArray *tmpArray = [NSArray arrayWithArray:[TPUserDefault instance].offlineStatusList]; NSMutableArray *list = [NSMutableArray arrayWithArray:[TPUserDefault instance].offlineStatusList]; [tmpArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([obj[@"nodeId"] intValue] == commandTag) { float currentByte = [obj[@"currentByte"] floatValue]; currentByte = currentByte + bytes; NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:obj]; [dic setValue:[NSString stringWithFormat:@"%f",currentByte] forKey:@"currentByte"]; [list replaceObjectAtIndex:idx withObject:dic]; } }]; [TPUserDefault instance].offlineStatusList = list; } - (void)queDidFinish { [[NSNotificationCenter defaultCenter] postNotificationName:QUEDIDFINISH object:nil]; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation" - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { // TPLOG(@"Download success for URL: %@",location.description); [ASIHTTPRequest hideNetworkActivityIndicator]; __block NSString *fileName = @""; __block NSNumber *actionTag = nil; __block id delegate = nil; __block BOOL isAllTaskFinish = YES; [self.sessionTaskList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSURLSessionDownloadTask *task = obj[@"task"]; if (task.taskIdentifier == downloadTask.taskIdentifier) { fileName = obj[@"fileName"]; actionTag = obj[@"actionTag"]; delegate = obj[@"delegate"]; [obj setValue:@"1" forKey:@"finish"]; } [[TPUserDefault instance].offlineStatusList enumerateObjectsUsingBlock:^(id item, NSUInteger index, BOOL *stop1) { if ([item[@"nodeId"] intValue] == [obj[@"actionTag"] intValue]) { if ([item[@"isSelected"] intValue] == 1) { NSString *finish = obj[@"finish"]; if (!finish || isBlankString(finish) || [finish intValue] != 1) { isAllTaskFinish = NO; } } } }]; }]; //通知已成功下载消息给相关代理 if (!isBlankString(fileName)) { NSURL *destination = [NSURL URLWithString:[@"file://" stringByAppendingString:ConfigPath(fileName)]]; TPLOG(@"%@",ConfigPath(fileName)); if ([self copyTempFileAtURL:location toDestination:destination]) { dispatch_async(dispatch_get_main_queue(), ^{ if ([delegate respondsToSelector:@selector(remoteResponsSuccess:withResponsData:)]) { [delegate remoteResponsSuccess:[actionTag intValue] withResponsData:fileName]; } if (isAllTaskFinish) { [[NSNotificationCenter defaultCenter] postNotificationName:QUEDIDFINISH object:nil]; ShowTextMessage(@"离线下载完成"); } }); } }else { TPLOG(@"文件名不存在,无法完成下载!!!"); } } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { if (![UIApplication sharedApplication].networkActivityIndicatorVisible) { [ASIHTTPRequest showNetworkActivityIndicator]; } // double currentProgress = totalBytesWritten/(double)totalBytesExpectedToWrite; // TPLOG(@"%f",currentProgress); __block NSNumber *actionTag = nil; [self.sessionTaskList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSURLSessionDownloadTask *task = obj[@"task"]; if (task.taskIdentifier == downloadTask.taskIdentifier) { actionTag = obj[@"actionTag"]; } }]; int commandTag = [actionTag intValue]; NSArray *tmpArray = [NSArray arrayWithArray:[TPUserDefault instance].offlineStatusList]; NSMutableArray *list = [NSMutableArray arrayWithArray:[TPUserDefault instance].offlineStatusList]; [tmpArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([obj[@"nodeId"] intValue] == commandTag) { NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:obj]; float currentByte = totalBytesWritten; [dic setValue:[NSString stringWithFormat:@"%f",currentByte] forKey:@"currentByte"]; [list replaceObjectAtIndex:idx withObject:dic]; } }]; [TPUserDefault instance].offlineStatusList = list; } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { if (![UIApplication sharedApplication].networkActivityIndicatorVisible) { [ASIHTTPRequest showNetworkActivityIndicator]; } // double currentProgress = totalBytesWritten/(double)totalBytesExpectedToWrite; // TPLOG(@"%f",currentProgress); __block NSNumber *actionTag = nil; [self.sessionTaskList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSURLSessionDownloadTask *task = obj[@"task"]; if (task.taskIdentifier == downloadTask.taskIdentifier) { actionTag = obj[@"actionTag"]; } }]; int commandTag = [actionTag intValue]; NSArray *tmpArray = [NSArray arrayWithArray:[TPUserDefault instance].offlineStatusList]; NSMutableArray *list = [NSMutableArray arrayWithArray:[TPUserDefault instance].offlineStatusList]; [tmpArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([obj[@"nodeId"] intValue] == commandTag) { NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:obj]; float currentByte = fileOffset; [dic setValue:[NSString stringWithFormat:@"%f",currentByte] forKey:@"currentByte"]; [list replaceObjectAtIndex:idx withObject:dic]; } }]; [TPUserDefault instance].offlineStatusList = list; } //后台回调给前台应用代码 - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate]; if (appDelegate.backgroundSessionCompletionHandler) { void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler; appDelegate.backgroundSessionCompletionHandler = nil; completionHandler(); } NSLog(@"所有任务已完成!"); [ASIHTTPRequest hideNetworkActivityIndicator]; } //下载终止回调(成功or失败) - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { if (error == nil) { NSLog(@"任务: %@ 成功完成", task); }else { NSLog(@"任务: %@ 发生错误: %@", task, [error localizedDescription]); } double progress = (double)task.countOfBytesReceived / (double)task.countOfBytesExpectedToReceive; NSLog(@"completeProgress:%f",progress); [ASIHTTPRequest hideNetworkActivityIndicator]; } #pragma clang diagnostic pop // 将JSON串转化为字典或者数组 - (id)toArrayOrNSDictionary:(NSData *)jsonData{ NSError *error = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error]; if (jsonObject != nil && error == nil){ return jsonObject; }else{ // 解析错误 return nil; } } //json容错处理 - (NSString*)dealResponseStringBeforeChange:(NSString*)responseString { responseString = [responseString stringByReplacingOccurrencesOfString:@"\\'" withString:@"'"]; if (![responseString isMatchedByRegex:@"\\\""]) { responseString = [responseString stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"]; } /** * bug:5328(224有个话题,进入后提示“服务器连接异常,请检查网络”) */ responseString = [responseString stringByReplacingOccurrencesOfString:@"\\'́" withString:@"'́"]; /** * bug:5208(话题详情页,有一个话题,加载不了) */ return responseString; } #pragma mark - 解析xml -(void)parseXMLData:(NSData *)data comlete:(void(^)(BOOL success,id responseData))completion{ dispatch_queue_t reentrantAvoidanceQueue = dispatch_queue_create("reentrantAvoidanceQueue", DISPATCH_QUEUE_SERIAL); dispatch_async(reentrantAvoidanceQueue, ^{ self.xmlFinishHandler = completion; //1.创建解析器 NSXMLParser *parser=[[NSXMLParser alloc]initWithData:data]; //2.设置代理 parser.delegate=self; //3.开始解析 if (![parser parse]) { if (self.xmlFinishHandler) { self.xmlFinishHandler(NO,nil); self.xmlFinishHandler = nil; } } }); dispatch_sync(reentrantAvoidanceQueue, ^{ }); } - (void)parserDidStartDocument:(NSXMLParser *)parser { self.xmlDic = [NSMutableDictionary dictionary]; } - (void)parserDidEndDocument:(NSXMLParser *)parser { if (self.xmlFinishHandler) { self.xmlFinishHandler(YES,self.xmlDic); self.xmlFinishHandler = nil; } } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { self.lastXMLStr = elementName; } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (![string isMatchedByRegex:@"http"] && [string isMatchedByRegex:@"="]) { NSArray *list = [string componentsSeparatedByRegex:@"="]; if (list.count < 2) { return; } [self.xmlDic setValue:list[1] forKey:list[0]]; }else { if (isBlankString([self.xmlDic valueForKey:self.lastXMLStr])) { [self.xmlDic setValue:string forKey:self.lastXMLStr]; } } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { } @end