Search code examples
iosobjective-cuitableviewfacebook-sdk-3.0

Loading Facebook data into a table view


I am stuck on the PROPER way to get all a user's Facebook friends and load it into a table view (I would simply use FBFriendPickerViewController but its ugly and it doesn't appear that you can fix that)

All I want is the profile picture in the cell imageView and name in the cell textLabel, simple as that.

Doing it with NSURL/NSData doesn't crop the images, Id much rather use FBProfilePictureView so please try to use that in any solutions. Thanks!

Get data from Facebook

-(void)facebookOpenSession {

    if (FBSession.activeSession.isOpen) {
        [[FBRequest requestForMyFriends] startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {

            if (error) {
                // handle error
            } else {
                self.facebookFriends = [NSArray arrayWithArray:[result objectForKey:@"data"]];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"facebookRequestForMyFriends" object:self];
            }
        }];
    }
}

Configure data into cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    // Configure the cell...
    NSDictionary<FBGraphUser> *friend = [self.facebookFriends objectAtIndex:indexPath.row];
    cell.textLabel.text = friend.name;

    NSURL *profilePictureUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=normal", friend.id]];

    NSData *profilePictureData = [NSData dataWithContentsOfURL:profilePictureUrl];

    cell.imageView.image = [UIImage imageWithData:profilePictureData];

    return cell;
}

How do people learn how to make all these things with the Facebook SDK, I spent almost 4 hours trying to do what I described above and I feel like I am completely missing something.


Solution

  • There are several open source libraries that make the task of downloading an image easy. My favorite is AFNetworking, but there's also SDWebImage. Using one of these categories, your task becomes as simple as:

    [myImageView setImageURL:"http://test.com/test.jpg"];
    

    Even if you don't want to use these libraries, don't do it the way you're currently attempting it (i.e. [NSData dataWithContentsOfURL:profilePictureUrl]). I believe that is a synchronous operation that will block your UI. Use code from one of the 2 links above, or make your own UIImageView category.