I've been trying to get a value from inside a block for a few hours now, I can't understand how to use the handlers on completion and literally everything.
Here's my code:
+ (void)downloadUserID:(void(^)(NSString *result))handler {
//Now redirect to assignments page
__block NSMutableString *returnString = [[NSMutableString alloc] init]; //'__block' so that it has a direct connection to both scopes, in the method AND in the block
NSURL *homeURL = [NSURL URLWithString:@"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage"];
NSMutableURLRequest *requestHome = [[NSMutableURLRequest alloc] initWithURL:homeURL];
[requestHome setHTTPMethod:@"GET"]; // this looks like GET request, not POST
[NSURLConnection sendAsynchronousRequest:requestHome queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *homeResponse, NSData *homeData, NSError *homeError) {
// do whatever with the data...and errors
if ([homeData length] > 0 && homeError == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:homeData options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
//NSLog(@"Response was = %@", responseJSON);
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
returnString = (@"Response was not JSON (from home), it was = %@", [[NSMutableString alloc] initWithData:homeData encoding:NSUTF8StringEncoding]);
//NSLog(returnString);
}
}
else {
//NSLog(@"error: %@", homeError);
}
}];
//NSLog(@"myResult: %@", [[NSString alloc] initWithData:myResult encoding:NSUTF8StringEncoding]);
handler(returnString);
}
- (void)getUserID {
[TClient downloadUserID:^(NSString *getIt){
NSLog([NSString stringWithFormat:@"From get userID %@", getIt]);
}];
}
So I'm trying to NSLog the returnString
from the downloadUserID
method.
I first tried returning, then I realized you can't do a return from inside a block. So now I've been trying to do it with the :(void(^)(NSString *result))handler
to try and access it from another class method.
So I'm calling downloadUserID
from the getUserID
method, and trying to log the returnString
string. It just keeps going to nil. It just prints From get userID
and nothing else.
How do I access the returnString
that's inside the block of the downloadUserID
method?
The problem is not the
block
itself, the problem is realizing that the block is executed asynchronously.In your code, at the time you call
handler(returnString);
the block is probably still executing on another thread, so there's no way you can catch the value at this point.Probably what you want to do is move that line inside the block (probably at the end, before the closing braces).