Reputation: 2154
When I want to get userID from Facebook, I need to wait the API "startWithCompletionHandler" to send me back the userID, then I continue my task. Just like the code listed below.
But I can not use dispatch_semaphore or dispatch_group to wait for the api to callback. Except for completionHandler, any other solution like "blockAndWait" in MagicalRecord that can help me solve question like this?
Also, the solution listed below isn't working. It seems blocked the main thread, so it'll keep logging "WAITING" and can not pop up the Facebook login view.
-(void)getAccountIDAndWait{
__block BOOL isFinish = NO;
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *aUser, NSError *error) {
if (error) {
NSLog(@"bug in getAccountIDAndWait");
return;
}
self.accountID = [aUser objectForKey:@"id"];
isFinish = YES;
}];
while(isFinish==NO){
sleep(0.1);
NSLog(@"WAITING");
}
}
Upvotes: 0
Views: 1126
Reputation: 8294
Expanding on what Chuck said I've slightly modified your code to allow the getAccountIdAndWait
function to finish (and thus the main thread to idle) and when the completionHandler is called it will call the doTheNextThing
function.
-(void)getAccountIDAndWait{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *aUser, NSError *error) {
if (error) {
NSLog(@"bug in getAccountIDAndWait");
return;
}
self.accountID = [aUser objectForKey:@"id"];
[self doTheNextThing];
}];
}
Upvotes: 1
Reputation: 237010
The approach you are using there is blocking. As you correctly observe, this is not really what you want. The design intent here is for you to put things that you want to happen after the request completes in the completion handler.
Upvotes: 0