问题
I want the function do not return until the AFHTTPRequestOperation
finished, but I did not know how to do it, thanks in advance.
-(BOOL)download
{
BOOL ret = TRUE;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
ret = [self handle:data];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
}];
[operation start];
return ret ;
}
回答1:
Your design is incorrect.
AFHTTPRequestOperation
is asynchronous so you cannot (and you shouldn't) treat it in a synchronous way. You have to modify your workflow in order to use the completion or failure blocks of the AFHTTPRequestOperation
.
回答2:
Since AFNetworking is asynchronous this isn't possible. When using async requests you should always call your finishing code within the success/finish block.
If you explain where you are using the download method and why you need to know when it's finished I can help explain/ help you design it better.
回答3:
I would agree with the others above that generally you should stick with AFNetworking Asynchronous nature, but there are ways to cause pseudo synchronous code to run for AFNetworking requests.
Using your example the code below should work.
-(BOOL)download {
BOOL ret = TRUE;
__block BOOL complete = NO;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
ret = [self handle:data];
complete = YES;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
complete = YES;
}];
[operation start];
while(complete == NO) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
return ret;
}
I have found this kind of usage to be particularly useful with unit testing API's. Nesting can become quite annoying if you have to do API calls just to get to the call you want to test. This is a nifty tool to get around that.
来源:https://stackoverflow.com/questions/14545164/how-to-make-function-to-return-after-the-afhttprequestoperation-has-done