I’ve a server where I request some data.
I’m checking if an image with certain name exists on it and I need to return a BOOL value (YES or NO), but I don’t know how to do it, because asynchronous request calls a callback when it’s finished, so when it finishes method has finished long time ago and it don’t return BOOL value and I don’t use synchronous request because it blocks main thread.
Here’s my code (I know it’s wrong, but I write it anyway to show an example of what I wanna do, cause my english is not so well):
- (BOOL)imageDoesExistsOnTheServer:(NSString *)imageName {
BOOL exists;
NSString * query = [[NSString alloc] initWithFormat:@"request=IMAGE&imageName=%@", imageName];
DREasyURLRequest * imageExistsRequest = [[DREasyURLRequest alloc] initForSendDataToServerWithURLString:@"http://xxxxx.xxxxx/file.php" query:query];
[imageExistsRequest sendAsynchronouslyWithCompletionForStringAsResponse:^(NSString *receivedResponse) {
if ([receivedResponse isEqualToString:@"YES"]) {
__block BOOL exists = YES;
} else {
__block BOOL exists = NO;
}
}];
return exists;
}
(DREasyURLRequest is a subclass of NSMutableURLRequest I’ve created to save some code, but sendAsynchronouslyWithCompletionForStringAsResponse: does absolutely the same as asynchronous NSMutableURLRequest method.
Can you guys help me?
P.D: I know, this code looks SO bad hahaha but I don’t have idea about what to do…
The block is not called by your code, so you cannot use
returnto provide anything to your code. Instead, stop thinking about return values, and start thinking about behaviour. You want something to happen when you get a positive response, and you want something to happen when you get a negative response. So write methods for each of these behaviours, and call them at the appropriate places in your blocks.