我试图在GCD中呼叫我的ASIHTTPRequest
。有时,comletion块和失败的块没有执行。我想要做的是,在此请求完成后,我必须在另一个ASIHTTPRequest
中使用返回的数据。那么如何改进这段代码:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
[request setCompletionBlock:^{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
NSData *_responseData = [request responseData];
NSString *response = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding] ;
self.albumDic = [response JSONValue];
[response release];
dispatch_async(dispatch_get_main_queue(), ^{
[self GetDictionary:self.albumDic];
});
});
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(@"Error : %@", error.localizedDescription);
}];
[request startSynchronous];
答案 0 :(得分:1)
不要那样走。你正在对线程进行线程处理(GCD使用线程,异步使用ASIHTTPRequest也是如此)。
使用ASINetworkQueue - 阅读here
以下是一种使用它的简单方法:
- (void)addRequestsToNetworkQueue:(NSArray *)requests {
// Stop anything already in the queue before removing it
[[self networkQueue] cancelAllOperations];
// Creating a new queue each time we use it means we don't have to worry about clearing delegates or resetting progress tracking
[self setNetworkQueue:[ASINetworkQueue queue]];
[[self networkQueue] setDelegate:self];
[[self networkQueue] setRequestDidFinishSelector:@selector(requestFinished:)];
[[self networkQueue] setRequestDidFailSelector:@selector(requestFailed:)];
[[self networkQueue] setQueueDidFinishSelector:@selector(queueFinished:)];
//Add all requests to queue
for (ASIHTTPRequest *req in requests) {
[[self networkQueue] addOperation:req];
}
//Start queue
[[self networkQueue] go];
}
ASINetworkQueue提供了许多委托方法(大多数也可以自定义),因此您可以在请求完成后更新GUI等等。它是异步的,因此不需要GCD。