Facebook Developers
DocsToolsSupportNewsApps
Log In
  • Social Plugins
  • Facebook Login
  • Open Graph
  • Facebook APIs
  • Games
  • Media
  • Payments
  • App Center
  • Promote Your App
  • iOS
  • Android
  • Web
  • Technology Partners
  • Topics
    • Facebook SDK for iOS
  • Authentication
    • Using Facebook Login
    • Adding Facebook Login
    • iOS 6 Integration
    • Understanding Sessions
    • Handling App Links
  • Data Access
    • Fetch User Data
    • Run FQL Queries
  • Sharing & Distribution
    • Sharing on iOS
    • Publish to Feed
    • iOS Share Sheet
    • Feed Dialog
    • Link To Your Native App
    • Send Requests
    • Setup for App Center
  • Customization
    • Add Search to Friend Selector
    • Manage Your Own Token Cache
    • Share an App ID Across Apps
  • Optimization
    • Batch Requests
    • Caching
    • Select Friends by Device
    • Handling Errors

Select Friends by Device

Documentation › Select Friends by Device

The Facebook SDK for iOS includes an FBFriendPickerViewController control object that makes it simple to add a friend selector to your app. The friend selector can filter the friends you display.

You may want to restrict the friends that display to show only those with specific devices. As an example, you may want to target friends that use platforms you support for a subsequent invite to use your app. This article guides you through how you can use a query for friend device data to filter the friends in the friend selector.

This document walks through the following topics:

  • Prerequisites
  • Sample Overview
  • Step 1: Set Up the Friend Selector Trigger
  • Step 2: Set Up the Friend Selector and Query Device Data
  • Step 3: Filter the Friend Selector with Device Data
  • Troubleshooting
  • Additional Info

Prerequisites

Before you begin, make sure you've already set up Facebook Login. This ensures you have the prerequisites and your app is ready for additional Facebook integration.


Sample Overview

The completed sample allows users to log in with Facebook and select friends with iOS devices. In this simple sample, we'll echo back the selected friends.

The implementation builds on top of Facebook Login, adding a button the user can click to show the friend selector. The friend selector is configured to display Done and Cancel buttons that dismiss the picker. The displayed friends are filtered to only include friends with iOS devices.

The friend selector displays with the FBFriendPickerViewController Facebook SDK object. After the object is initialized, call the loadData instance method to load and set up the initial friend selection. During the initialization step, the object is configured to request friend device data. During the display step, the FBFriendPickerDelegate protocol's friendPickerViewController:shouldIncludeUser: method is used to filter the friends.

Additional FBFriendPickerDelegate methods are defined to handle the friend selector Cancel and Done button actions. If the Done button is tapped, the selected friends echo through NSLog. Both cases dismiss the modal view controller.

Now that you have an overview of the UI and functionality, let's show you the code.


Step 1: Set Up the Friend Selector Trigger

In this step, you'll add a button in the initial view controller. When the user clicks the button, the friend selector displays.

Make the following changes in your main view controller's nib file:

  • Add a Round Rect Button object to the view. Set the button title to ''Select Friends''.
  • Make the ''Select Friends'' button hidden initially. You only want to display the button after the user authenticates.
  • Add an action to the ''Select Friends'' button and attach this action to your main view controller's implementation file. Name the action ''selectFriendsButtonAction''.
  • Add an outlet for the ''Select Friends'' button to your view controller's implementation file so that it's private. Name the outlet ''selectFriendsButton''.

When you've completed these steps, your implementation file should have the defined outlet and an empty selectFriendsButtonAction: action method.

If you followed the Facebook Login doc, you should have a sessionStateChanged: method defined in your view controller implementation file that controls the logged-in and logged-out UI. Modify this method to show the friend selector button only when the user is authenticated:

- (void)sessionStateChanged:(NSNotification*)notification {
    if (FBSession.activeSession.isOpen) {
        self.selectFriendsButton.hidden = NO;
        [self.authButton setTitle:@"Logout" forState:UIControlStateNormal];
    } else {
        self.selectFriendsButton.hidden = YES;
        [self.authButton setTitle:@"Login" forState:UIControlStateNormal];
    }
}

Step 2: Set Up the Friend Selector and Query Device Data

In this step, you'll set up the friend selector and ask for friend device data when requesting the friend data. You won't do anything with the device data, so the friends in the selector won't be filtered. You'll handle filtering based on device data in the next step.

Open the view controller implementation file and add the FBFriendPickerDelegate as one of the protocols the view controller implementation conforms to. Add this delegate to the view controller implementation.

@interface ViewController ()
<FBFriendPickerDelegate>

Next, fill out the selectFriendsButtonAction: method implementation to trigger the friend selector display. In the code, you'll do the following:

  • Initialize a FBFriendPickerViewController object.
  • Configure the properties, which includes asking for friend device data.
  • Set the delegate to the current class.
  • Load the data.
  • Show the friend selector modally.
- (IBAction)selectFriendsButtonAction:(id)sender {    
    // Initialize the friend picker
    FBFriendPickerViewController *friendPickerController = 
        [[FBFriendPickerViewController alloc] init];

    // Configure the picker ...
    friendPickerController.title = @"Select Friends";
    // Set this view controller as the friend picker delegate
    friendPickerController.delegate = self;
    // Ask for friend device data
    friendPickerController.fieldsForRequest = 
        [NSSet setWithObjects:@"devices", nil];

    // Fetch the data
    [friendPickerController loadData];

    // Present view controller modally.e the deprecated
    if ([self
         respondsToSelector:@selector(presentViewController:animated:completion:)]) {
        // iOS 5+
        [self presentViewController:friendPickerController 
                           animated:YES 
                         completion:nil];
    } else {
        [self presentModalViewController:friendPickerController animated:YES];
    }
}

Note the configuration that requests device data along with basic friend data:

friendPickerController.fieldsForRequest = [NSSet setWithObjects:@"devices", nil];

Next, implement the FBFriendPickerDelegate delegate methods to handle the Done and Cancel buttons. For the Done button, you'll log any friends selected and dismiss the modal view controller:

- (void)facebookViewControllerCancelWasPressed:(id)sender
{
    NSLog(@"Friend selection cancelled.");
    [self dismissModalViewControllerAnimated:YES];

}

- (void)facebookViewControllerDoneWasPressed:(id)sender
{
    FBFriendPickerViewController *fpc = (FBFriendPickerViewController *)sender;
    for (id<FBGraphUser> user in fpc.selection) {
        NSLog(@"Friend selected: %@", user.name);
    }
    [self dismissModalViewControllerAnimated:YES];
}

Build and run the project to make sure it runs without errors. Tap the ''Login'' button to log in with Facebook. Once you're authenticated, you should see the ''Select Friends'' button. Click ''Select Friends'' to show the friend selector. Select a few friends and tap on the Done button. You should see an Xcode console log similar to the following:

2012-09-07 09:43:32.084 FriendPickerDeviceFilterHowTo[84313:c07] Friend selected: Alan McConnell
2012-09-07 09:43:32.085 FriendPickerDeviceFilterHowTo[84313:c07] Friend selected: Ali Parr

Step 3: Filter the Friend Selector with Device Data

In the previous step, you requested device data to be returned with default friend data. The friend data looks similar to this:

devices =  (
    {
         hardware = iPhone;
         os = iOS;
    },
    {
         os = Android;
    },
                                                {
         hardware = iPad;
         os = iOS;
    }
);
"first_name" = Zoran;
id = 15150;
...

In this step, you'll use the FBFriendPickerDelegate to filter the friend device data returned and show only friends using iOS devices. The friendPickerViewController:shouldIncludeUser: method of the FBFriendPickerDelegate protocol filters the friends.

First, you need to define a new protocol to represent friend info that includes device data. This new protocol should also conform to FBGraphUser, the protocol that defines basic friend info. To define the new protocol, add a new file to the project. Select the Objective-C protocol template and name the protocol FriendProtocols.

Next, open up the newly added FriendProtocols.h file. You'll create your own protocol definition, so replace the contents of the file with the following:

#import <Foundation/Foundation.h>
#import <FacebookSDK/FacebookSDK.h>

@protocol FBGraphUserExtraFields <FBGraphUser>

@property (nonatomic, retain) NSArray *devices;

@end

Now, open up your view controller implementation file and include your new protocol:

#import "FriendProtocols.h"

Finally, implement the following FBFriendPickerDelegate method to show friends with iOS devices:

- (BOOL)friendPickerViewController:(FBFriendPickerViewController *)friendPicker
                 shouldIncludeUser:(id&lt;FBGraphUserExtraFields>)user
{
    NSArray *deviceData = user.devices;
    // Loop through list of devices
    for (NSDictionary *deviceObject in deviceData) {
        // Check if there is a device match
        if ([@"iOS" isEqualToString:
             [deviceObject objectForKey:@"os"]]) {
            // Friend is an iOS user, include them in the display
            return YES;
        }
    }
    // Friend is not an iOS user, do not include them
    return NO;
}

Build and run the project to make sure it runs without errors. Once you're authenticated, click Select Friends to show the friend selector. Verify that only iOS friends display by using the Graph API Explorer and entering the query me/friends?fields=name,devices:


Troubleshooting

If you have any issues with custom filtering you need to do, turn on debugging for the requests. Add this code before any requests:

[FBSettings setLoggingBehavior:
    [NSSet setWithObject:FBLoggingBehaviorFBRequests]];

You'll be able to debug any issues by viewing requests and responses from the servers.


Additional Info

  • How Tos Samples: includes the completed sample.
  • FBFriendPickerViewController: reference for the friend selector class.
  • FBFriendPickerDelegate: reference for the friend selector delegate protocol.
  • Facebook SDK Tutorial: tutorial including a friend selector walk-through.
  • FriendPickerSample: simple sample from the SDK that shows a friend selector.
Updated about a week ago
Facebook © 2013 · English (US)
AboutAdvertisingCareersPlatform PoliciesPrivacy Policy