Here i am trying to call my ASIHTTP request in a GCD . But Completion block and failed blocks are not executing

我的未来我决定 提交于 2019-12-12 01:50:36

问题


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

回答1:


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

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 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.



来源:https://stackoverflow.com/questions/7702015/here-i-am-trying-to-call-my-asihttp-request-in-a-gcd-but-completion-block-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!