Reputation: 642
I am using AFNetworking to receive JSON back from the server, and I use this JSON to determine the return value for my Objective-C function. Regardless of what the JSON is though, the value of d doesn't change from when it is initialized (as a false value). Why is this happening? My code is as follows:
-(BOOL)someFunction{
__block BOOL d;
d = FALSE;
//the value of d is no longer changed
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *req, NSHTTPURLResponse *response, id jsonObject) {
if(![[jsonObject allKeys] containsObject:@"someString"]){
d = TRUE;
}
else {
d = FALSE;
}
}
failure:^(NSURLRequest *req, NSHTTPURLResponse *response, NSError *error, id jsonObject) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Alert"
message: @"Could not connect to server!"
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
d = FALSE;
}];
[operation start];
return d;
}
Upvotes: 1
Views: 169
Reputation: 4180
You should use an async function with a completion block that returns a success BOOL.
- (void)myBeautifulFunction
{
[self someFunctionWithCompletion:^(BOOL success) {
if (!success) {
[self showAlert];
}
}];
}
- (void)someFunctionWithCompletion:(void (^)(BOOL success))completion
{
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *req, NSHTTPURLResponse *response, id jsonObject) {
if (![[jsonObject allKeys] containsObject:@"someString"]){
if (completion) {
completion(YES);
}
} else {
if (completion) {
completion(NO);
}
}
} failure:^(NSURLRequest *req, NSHTTPURLResponse *response, NSError *error, id jsonObject) {
if (completion) {
completion(NO);
}
}];
[operation start];
}
Upvotes: 2
Reputation: 11174
The operation will be performed asynchronously but you return the value of d
synchronously. You should trigger whatever requires the value of d from the operations completion block
Upvotes: 0