本文介绍了在这里,我试图在GCD中调用我的ASIHTTP请求。但是没有执行完成块和失败的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我试图在GCD中调用我的 ASIHTTPRequest 。有时,comletion块和失败的块没有执行。我想要做的是,在此请求完成后,我必须在另一个 ASIHTTPRequest 中使用返回的数据。那么如何改进这段代码:

Here i am trying to call my ASIHTTPRequest in a GCD. Sometimes the comletion blocks and failed blocks are not executing. What i want to do is, after this request finished, i have to use the returned data in a another ASIHTTPRequest. So how to improve this code:

 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];


推荐答案

不要这样做。你正在对线程进行线程处理(GCD使用线程,异步使用ASIHTTPRequest也是如此)。

Don't go that way. You're doing threading on threading (GCD uses threading and so does ASIHTTPRequest when used asynchronously).

使用ASINetworkQueue代替 - 阅读它

Use ASINetworkQueue instead - read about it here

这是一种可以使用它的简单方法:

Here is a simple way you could use it:

- (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。

ASINetworkQueue provides many delegate methods (most are also customizable), so you can update the GUI when a request is finished and so forth. It is asynchronous, so GCD is unnecessary.

这篇关于在这里,我试图在GCD中调用我的ASIHTTP请求。但是没有执行完成块和失败的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 07:49