News for Developers

Developer News
How-To: Use the Graph API to Upload a Video (iOS)

As part of our continuing series of “How-Tos,” we will show you how to upload a video to a user’s profile. Videos are a deeply integrated part of the Facebook experience. Publishing videos adds a video to user’s profile and also generates a newsfeed story about the video, with a link to your app. This is a great way to engage the user’s friends and drive interest for and traffic back to your app.

Here’s a sample video published on a user profile from my “Video Upload Test” app and the News Feed story published as a result.

In order to publish a video to a user’s profile, you must have the publish_stream permission. With that granted, you can upload a video by issuing an HTTP POST request with the video content and an optional title and description to the https://graph.facebook.com/USER_ID/videos Graph API connection.

In our How-To app we will upload a video that is packaged as part of the app. The app will show the user a button that, when clicked, will ask the user to log into Facebook, authorize the app, then upload the packaged video.

Setting Up Your Development Environment

This How-To assumes you are familiar with iOS development. You can set up your development environment by installing Xcode, Git, and getting the latest Facebook iOS SDK:

  1. Install Xcode (http://developer.apple.com/xcode/)
  2. Install Git (http://git-scm.com/)
  3. Clone the Facebook iOS GitHub repository: git clone git://github.com/facebook/facebook-ios-sdk.git

Next you need to get a Facebook app id for the How-To app you will build.

Creating a Facebook App

Go to developers.facebook.com/apps and authorize the Developer app if prompted. Then click on Create New App and follow the prompts to create a new mobile app. If you are not a verified developer then you will need to go through some extra steps to get verified.

Once you have created a new app, note the app id that is displayed on the summary page. You will be using this app id inside your iOS app.

Setting Up The iOS Project

Step 1. Start a New Project

Open Xcode and create a new View-based Application project named VideoUploadTest.

In order to use the iOS Facebook SDK, the source files from that SDK project must be brought into the app project. This can be done a number of different ways, but the easiest way is to just drag the src folder from the local Git repository for the SDK (e.g. ~/facebook-ios-sdk/src) into the app Xcode project

Step 2. Add a Sample Video to your Project

Find a video file and add is as a resource to your project. Our sample video is called sample.mov and in our project we copied it under the Supporting Files folder.

Once your Xcode project is set up it should look similar to the following:

Writing the Code

Step 1. Set up the Facebook Class

Setting up the Facebook class involves importing the Facebook SDK header files, declaring that the view controller will handle the Facebook delegate callbacks, and instantiating the Facebook class instance.

Make these changes in the view controller header file - VideoUploadTestViewController.h:

Import the Facebook SDK header files by adding the line:

#import "Facebook.h"

Define the Facebook session and request protocols as part of the view controller interface:

<FBSessionDelegate, FBRequestDelegate>

Declare the Facebook instance by adding the instance variable:

Facebook *facebook;

Add a property for the instance of the Facebook class:

@property (nonatomic, retain) Facebook *facebook;

Make these changes in the view controller implementation file (VideoUploadTestViewController.m).

Synthesize the Facebook property and release the Facebook instance in the dealloc method:

@synthesize facebook;

- (void)dealloc
{
    [facebook release];
    [super dealloc];
}

Create an instance of the Facebook class in the viewDidLoad method:

- (void)viewDidLoad
{
    facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID"];
}

Replace YOUR_APP_ID with the app id you noted down from the Facebook Developer portal.

Step 2. Set up Permissions and the Authentication Handler

Our app flow requires you to set up a button with the title “Upload Video” . When the button is clicked the user will be prompted to log in then authorize the app.

Add a UIButton to ViewUploadTestViewController.xib NIB file and attach it to an IBAction called buttonClicked in the view controller implementation file.

In the buttonClicked method, call the Facebook authorization code

- (IBAction)buttonClicked:(id)sender {
    NSArray* permissions = [[NSArray alloc] initWithObjects:
                            @"publish_stream", nil];
    [facebook authorize:permissions delegate:self];
    [permissions release];
}

Step 3. Set up the Video Upload Graph API Call

When the user successfully authorizes the app you then upload the video. To do this you implement the fbDidLogin method of FBSessionDelegate protocol.

- (void)fbDidLogin {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"mov"];
    NSData *videoData = [NSData dataWithContentsOfFile:filePath];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   videoData, @"video.mov",
                                   @"video/quicktime", @"contentType",
                                   @"Video Test Title", @"title",
                                   @"Video Test Description", @"description",
                       nil];
    [facebook requestWithGraphPath:@"me/videos"
                         andParams:params
                     andHttpMethod:@"POST"
                       andDelegate:self];
}

You should also handle the error path by implementing the FBSessionDelegate protocol’s fbDidNotLogin: method.

-(void)fbDidNotLogin:(BOOL)cancelled {
    NSLog(@"did not login");
}

Step 4. Handle the Results

Once the video has been uploaded the FBRequestDelegate delegate will be notified. Implement the FBRequestDelegate methods to handle the request callbacks. To handle the success case, implement the request:didLoad: method. In the example below we are simply echoing the Graph API response through NSLog.

- (void)request:(FBRequest *)request didLoad:(id)result {
    if ([result isKindOfClass:[NSArray class]]) {
        result = [result objectAtIndex:0];
    }
    NSLog(@"Result of API call: %@", result);
}

You should also handle the error path by implementing the request: didFailWithError: method:

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
    NSLog(@"Failed with error: %@", [error localizedDescription]);
}

Step 5. Add Single Sign-On (SSO) Support

You can add SSO support to your app. This allows users sign into your app using their Facebook identity. If they are already signed into the Facebook iOS app on their device they do not have to even type a username or password.

Add the application:handleOpenURL: method to the AppDelegate (VideoUploadTestAppDelegate.m) with a call to the facebook instance:

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [[_viewController facebook] handleOpenURL:url];
}

This method is called by iOS when the Facebook App redirects to the app during the SSO process. The call to Facebook:handleOpenURL: provides the app with the user's credentials.

Finally, update the .plist file that handles configuration for the app. A specific URL needs to be registered in this file that uniquely identifies the app with iOS. Create a new row named URL types with a single item, URL Schemes, containing a single value, fbYOUR_APP_ID (the literal characters ‘fb’ followed by your app id).

For a step-by-step guide on implementing SSO see https://developers.dev.facebook.com/mobile/ios/.

Now that we have completed the code, we are ready to Build and Run the app.

Running The App

Click the Xcode Run button to run the app. Your simulator should launch and you should see the upload video button. Once you click on the button you may be asked to log into Facebook after which you will be asked to authorize the app.

                                            

When you click on ‘Allow’, the video will be uploaded to your profile and the Xcode output will show the id of the posted video.

NSLog sample output:

{
    id = 2276199950869;
}

You can log into www.facebook.com and check that your video is uploaded. Note that the upload process may take several minutes, depending on the size of the video and processing time after upload.

Setting Video Privacy

You can specify privacy settings when you upload a video. To do this, add the privacy parameter to your Graph API call. In the sample in this How-To, you can set privacy to “friends of friends” as follows:

NSDictionary *dictPrivacy = [NSDictionary     
           dictionaryWithObjectsAndKeys:@"FRIENDS_OF_FRIENDS",@"value",
           nil];
SBJSON *jsonWriter = [[SBJSON new] autorelease];
NSString *strPrivacy = [jsonWriter stringWithObject:dictPrivacy];

NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               videoData, @"video.mov",
                               @"video/quicktime", @"contentType",
                               @"Video Test Title", @"title",
                               @"Video Test Description", @"description",
                               strPrivacy, @"privacy",
                               nil];

After you make these changes, Build and Run the app. You can make a Graph API call to https://graph.facebook.com/VIDEO_ID with an access_token having read_stream permissions to verify the privacy settings of the uploaded video.

Refer to User and Video documentation for more details on the Video object.

You can download the complete Video Upload Test example as an Xcode project here.