Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook request thread problem

Alright I am kind of new to threads so I have this question. I am trying to get information of friends from Facebook, and I do not want to do that on the main thread. but for some reason when the request is not on the main thread the callback does never get called and I don't know why!

I have an Array with all the ID's from my friends and loop through this array and create an object of my custom class Friend (which gets all the information I need) with every ID. I add this object to an array. This friend object makes an request to Facebook and handles the response to get the data I want.

here is the code:

dispatch_async(dispatch_get_global_queue(0, 0), ^(void) {
            [self getFBFriendsInfo];
        }); 


 -(void)getFBFriendsInfo{

if (friendsInfoArray) {
    [friendsInfoArray removeAllObjects];
}
else{
    friendsInfoArray =[[NSMutableArray alloc]init];
}



for (int i=0; i<[UDID count]; i++) {
    NSString *udid = [UDID objectAtIndex:i];
    FriendsInfo *friend =[[FriendsInfo alloc] initWithFacebook:facebook andUdid:udid];
    [friendsInfoArray addObject:friend];
    [friend release];

}

dispatch_async(dispatch_get_main_queue(), ^(void) {
    [delegate friendsInfosAvailable:friendsInfoArray];
});

}

and in my custom class I do this:

[facebook requestWithGraphPath:udid andDelegate:self];

with this the callback's are never called! only if I do the request on the main thread it works:

dispatch_async(dispatch_get_main_queue(), ^(void) {
    [facebook requestWithGraphPath:udid andDelegate:self];


});
like image 475
BObereder Avatar asked Jan 18 '23 21:01

BObereder


1 Answers

This is why on a different thread you get no response:

Facebook will use NSURLConnection to perform requests. For the connection to work correctly the calling thread’s run loop must be operating in the default run loop mode (Read NSURLConnection class reference). When you use dispatch_async() there is no run loop operating in the default run loop mode (unless you are on the main dispatch queue, therefore running on the main thread). Hence, I figure the request isn't even sent (You can check that sniffing your network if you wish.).

So, in a nutshell, you should make your request on the main thread; as it is asynchronous, it wont freeze your app. Then, if the processing of the response is too expensive, handle it in the background.

I really hope this helps.

My best.

like image 193
Lio Avatar answered Feb 02 '23 09:02

Lio