how to make function to return after the AFHTTPRequestOperation has done

老子叫甜甜 提交于 2020-01-28 10:22:43

问题


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

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