This question already has an answer here:
I'm using AFNetworking
2 to GET data from server and I need to get back the responseObject
but no matter what I do i still get <null>
.
Here is the method which is sending GET request to server and in response it gets NSDictionary
which I want to use in another method...
- (void)getCurrentVersionsForTimetableWithID:(NSString *)timetableID
{
[[AFHTTPRequestOperationManager manager] GET:[NSString stringWithFormat:VERSIONS, timetableID] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Here I want to get responseObject
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Couldn't get current versions: %@", [error localizedDescription]);
}];
}
If I call this method everything works fine. But when I try to make it return NSDictionary
like this:
- (NSDictionary *)getCurrentVersionsForTimetableWithID:(NSString *)timetableID
{
__block NSDictionary *currentVersions;
[[AFHTTPRequestOperationManager manager] GET:[NSString stringWithFormat:VERSIONS, timetableID] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
currentVersions = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Couldn't get current versions: %@", [error localizedDescription]);
}];
return currentVersions;
}
I get <null>
value. I know this is happening because of async but how to solve this? I've tried to pass another completion block to this method but when I call it inside another one I still cannot assign the result to the variable... Please guys, help me!
I'm sure the problem with async calls, threads run in parallel and you return nil before you get actual data, so easy way (not the prefect! :) ) is to make it synchronous to wait for result:
try:
or better to use Michaels answer to return in completion block if you need it async, its a good way to return cached data before actual data coming.
Try this, I dont remember how a blocks is created in my head and im not on my mac. But i think its like this.
You want to pass in a completion block that takes NSDictionary as parameter:
To use it: