Facebook Developers
DocsToolsSupportNewsApps
Log In
  • Social Plugins
  • Facebook Login
  • Open Graph
  • Facebook APIs
  • Games
  • Payments
  • App Center
  • Promote Your App
  • iOS
  • Android
  • JavaScript
  • PHP
  • More SDKs
  • Topics
    • Facebook SDK for iOS
  • Getting Started
    • Getting Started with the Facebook SDK for iOS
    • Build, Distribute and Promote
  • iOS SDK Tutorial
    • Facebook iOS SDK Tutorial
    • 1 - Authenticate Using Facebook Login
    • 2 - Personalize
    • 3 - Show Friends
    • 4 - Show Nearby Places
    • 5 - Publish Open Graph Story
  • Games Tutorial
    • iOS Games Tutorial
    • 1 - Authenticate
    • 2 - Personalize
    • 3 - Invites and Requests
    • 4 - Bragging and News Feed
    • 5 - Publish Open Graph Story
  • Upgrading SDKs Tutorials
    • Upgrading from 3.2 to 3.5
    • Upgrading from 3.1 to 3.2
    • Upgrading from 3.0 to 3.1
    • Upgrading from 2.0 to 3.1

3 - Show Friends

Documentation › Facebook iOS SDK Tutorial › 3 - Show Friends

This tutorial outlines how to show a user's friends in your app with the Facebook SDK for iOS. This makes your app more engaging and feel more personal. To illustrate where friends come in the picture, let's look at the test app you're building.


The finished app will allow the user to select one or more friends, tag a current location, take a photo and publish a story with these details on timeline and news feed. This tutorial covers the friend selector flow. When you've finished these steps, your flow should look like this:

We'll walk you through setting up the home menu selection and implementing the friend selector flow.

To display the friend selector, use the FBFriendPickerViewController Facebook SDK object. To use this object, first initialize an instance through the initWithNibName:bundle: method. Once you have an instance, set the delegate method to define the object that will handle the FBFriendPickerDelegate notifications. Finally, call the loadData to initiate the API call to get the user's friends. You can then display the FBFriendPickerViewController to show the friend selector.

In this tutorial, you'll implement the FBFriendPickerDelegate method friendPickerViewControllerSelectionDidChange: that is notified when a user selects a friend. That delegate method will be passed the FBFriendPickerViewController instance and you'll use the selection property to retrieve the selected friends.

This tutorial walks through the following:

  • Step 1: Set Up the User Interface
  • Step 2: Set Up The Menu Display
  • Step 3: Show the Friend Selector
  • Step 4: Display Selected Friends
  • Next Steps
  • Related Samples

Note: Before you start this tutorial, make sure you've personalized your app.


Step 1: Set Up the User Interface

The UI you set up in this step corresponds to the home menu selection where one of the menu items triggers the friend selector display. The friend selector display is implemented programmatically.

Add the home menu in the SCViewController that is displayed when the user is authenticated. Make the following changes in SCViewController.xib:

  • Home Menu: Add a Table View object with the following properties: Style: Grouped; Show Selection on Touch: NO; Scrolling Enabled: NO; Background: FFFFFF; Section Height Header: 10; Section Height Footer: 10; X, Y (offset): 0, 118; Width, Height (size): 320, 342; Autosizing: flexible bottom margin;

When you're done, your UI in Interface Builder should look like this:


Next, wire up the menu table to the SCViewController implementation file:

  • Create an outlet for the Table View object and call it menuTableView.
  • Connect the dataSource outlet to the File's Owner.
  • Connect the delegate outlet to the File's Owner.

Step 2: Set Up The Menu Display

Now add code to show the menu in the table view that was set up in SCViewController.xib.

First, in the SCViewController implementation file, add UITableViewDataSource and UITableViewDelegate to the list of protocols it conforms to:

@interface SCViewController ()
<UITableViewDataSource,
UITableViewDelegate> 

Next, add the UITableView data source and delegate methods.

The data in the menu table is defined as follows:

- (UITableViewCell *)tableView:(UITableView *)tableView 
      cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = (UITableViewCell*)[tableView 
        dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
            reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.textLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        cell.textLabel.lineBreakMode = UILineBreakModeTailTruncation;
        cell.textLabel.clipsToBounds = YES;

        cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
        cell.detailTextLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        cell.detailTextLabel.textColor = [UIColor colorWithRed:0.4 
                                                         green:0.6
                                                          blue:0.8 
                                                         alpha:1];
        cell.detailTextLabel.lineBreakMode = UILineBreakModeTailTruncation;
        cell.detailTextLabel.clipsToBounds = YES;
    }
    
    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = @"What are you eating?";
            cell.detailTextLabel.text = @"Select one";
            cell.imageView.image = [UIImage imageNamed:@"action-eating.png"];
            break;
            
        case 1:
            cell.textLabel.text = @"Where are you?";
            cell.detailTextLabel.text = @"Select one";
            cell.imageView.image = [UIImage imageNamed:@"action-location.png"];
            break;
            
        case 2:
            cell.textLabel.text = @"With whom?";
            cell.detailTextLabel.text = @"Select friends";
            cell.imageView.image = [UIImage imageNamed:@"action-people.png"];
            break;
            
        case 3:
            cell.textLabel.text = @"Got a picture?";
            cell.detailTextLabel.text = @"Take one";
            cell.imageView.image = [UIImage imageNamed:@"action-photo.png"];
            break;
            
        default:
            break;
    }

    return cell;
}

The menu table consists of one section with four menu items:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return 4;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

For now, set things up so tapping on any row does nothing. Wire up the friend selector after verifying the menu displays correctly.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Do nothing for now
}

You may have noticed that you have not set a title for the SCViewController view. Let's take care of that now. Add a title by adding the following statement at the end of the viewDidLoad method:

self.title = @"Scrumptious";

Build and run the project to make sure it runs without errors. Once you're authenticated, you should see the home menu selection list that includes the friend selector option.


Step 3: Show the Friend Selector

Create a property to hold the friend picker view controller that displays the friend selector:

@property (strong, nonatomic) FBFriendPickerViewController *friendPickerController;

Synthesize the new property:

@synthesize friendPickerController = _friendPickerController;

Next, make sure this view is released when the viewDidUnload method. Add this to the end of the method:

self.friendPickerController = nil;

Modify the tableView:didSelectRowAtIndexPath: delegate method to set up the friend selector using the FBFriendPickerViewController Facebook SDK control:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 2:
            if (!self.friendPickerController) {
                self.friendPickerController = [[FBFriendPickerViewController alloc] 
                    initWithNibName:nil bundle:nil];
                self.friendPickerController.title = @"Select friends";
            }

            [self.friendPickerController loadData];
            [self.navigationController pushViewController:self.friendPickerController 
                animated:true];
    }
}

Build and run the project to make sure it runs without errors. Once you see the home menu selection, select the ''With whom?'' menu option. You should see a list of your friends to choose from. Selecting a friend and tapping the Back button should do nothing at this point. You will add the functionality that saves the selected friend next.


Step 4: Display Selected Friends

First, add FBFriendPickerDelegate to the list of protocols that the SCViewController conforms to.

Modify the tableView:didSelectRowAtIndexPath: method to set the delegate that will handle the friend selector:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 2:
            if (!self.friendPickerController) {
                self.friendPickerController = [[FBFriendPickerViewController alloc] 
                    initWithNibName:nil bundle:nil];

                // Set the friend picker delegate
                self.friendPickerController.delegate = self;

                self.friendPickerController.title = @"Select friends";
            }

            [self.friendPickerController loadData];
            [self.navigationController pushViewController:self.friendPickerController 
                animated:true];
            break;
    }
}

When the view is deallocated, nil out the friend picker delegate. Add the dealloc method to do this:

- (void)dealloc
{
    _friendPickerController.delegate = nil;
}

Create a property to hold the friend selections.

@property (strong, nonatomic) NSArray* selectedFriends;

Synthesize:

@synthesize selectedFriends = _selectedFriends;

Display any selected friends in the friend selector menu option. Add two new helper methods that you will use to update the display:

- (void)updateCellIndex:(int)index withSubtitle:(NSString*)subtitle {
    UITableViewCell *cell = (UITableViewCell *)[self.menuTableView 
        cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    cell.detailTextLabel.text = subtitle;
}

- (void)updateSelections 
{

    NSString* friendsSubtitle = @"Select friends";
    int friendCount = self.selectedFriends.count;
    if (friendCount > 2) {
        // Just to mix things up, don't always show the first friend.
        id<FBGraphUser> randomFriend = 
            [self.selectedFriends objectAtIndex:arc4random() % friendCount];
        friendsSubtitle = [NSString stringWithFormat:@"%@ and %d others", 
            randomFriend.name,
            friendCount - 1];
    } else if (friendCount == 2) {
        id<FBGraphUser> friend1 = [self.selectedFriends objectAtIndex:0];
        id<FBGraphUser> friend2 = [self.selectedFriends objectAtIndex:1];
        friendsSubtitle = [NSString stringWithFormat:@"%@ and %@",
            friend1.name,
            friend2.name];
    } else if (friendCount == 1) {
        id<FBGraphUser> friend = [self.selectedFriends objectAtIndex:0];
        friendsSubtitle = friend.name;
    }
    [self updateCellIndex:2 withSubtitle:friendsSubtitle];
}

The updateSelections helper method controls how the friends are displayed. If one or two friends are selected, those friends' names will be displayed. If more than two friends are selected, a random friend's name will be displayed as well as a count value of the additional friends that have been selected.

Implement the FBFriendPickerDelegate method that will be notified of a friend selection and call the helper method you defined to update the table row display to show the selected friends:

- (void)friendPickerViewControllerSelectionDidChange:
(FBFriendPickerViewController *)friendPicker
{
    self.selectedFriends = friendPicker.selection;
    [self updateSelections];
}

Build and run the project to make sure it runs without errors. Tap the ''With whom?'' menu selection, and then select a friend from the friend selector. Tap the Back button. You should see the friend you selected in the ''With whom?'' row. Try selecting one or more friends to ensure that selected friends are displayed correctly.


Next Steps

Learn how to show the user a list of nearby places.


Related Samples

  • FriendPickerSample
Updated about 4 months ago
Facebook © 2013 · English (US)
AboutAdvertisingCareersPlatform PoliciesPrivacy Policy