Monday, 13 February 2012

How To Post on Facebook with Your iPhone App


Integrating Facebook into your app is a great way to let users share content from your app with their friends. For example, if you have an app where users can record their grades, why not add a button to let the users share their final grades with their friends at the end of the semester? It could be fun for the users, and could also let a lot more people know about your app.
The Facebook developers have made it quite easy to integrate Facebook in your iPhone app with a great SDK. This article will show you how to quickly and integrate Facebook into your iPhone app – and it comes with a simple example project to follow along with!
Update: Since writing this article, a new Facebook SDK (using the Graph API) has come out. This article does not cover that – it covers the old Facebook SDK (using the REST API), which is still available and operational at the time of this writing.
There have been several changes to the Facebook SDK since I wrote this article (early this year). I may update this article with the changes at some point, but until then no guarantees are made! :]

Register Your Application With Facebook

The first thing you have to do is to register your app with Facebook. It’s an extremely simple process:
The "Create Application" step in Facebook
  1. Go to the Facebook developers portal, log in, and allow access to the Developer application.
  2. Click the button “Set Up New Application”, give it a name (the name of your application will do), and click “Create Application”.
  3. Now you’ll be at a screen where you can edit the details of the application. You’ll probably want to set the description and logo, but the rest is really optional for now.
  4. Finally, record the values in “API Key” and the “Secret” sections. You’ll need those later!
  5. Update: smaug from the comments section mentioned that he had to set the iPhone application ID in the Advanced tab to the app ID for his app to get it to work – so you may need to set this as well if you have problems!

Add the Facebook iPhone SDK Into Your Project

Next, go to the Facebook iPhone SDK project page and click the “Download Source” button to pull down the latest copy of the SDK. Feel free to look through the project. In particular, the “Connect” sample project is a great demo of some of the most important functionality.
But for the purposes of this article, we’re going to dive straight into things! Adding the SDK into your project is easy:
Directory structure for sample project
Directory structure for sample project
  1. Move the SDK into a known location relative to your project. For example, I have my code in a folder called “Level Me Up”, and I put the SDK folder (which I named “facebook-iphone-sdk”) as a sibling folder.
  2. Open up the src\FBConnect.xcodeproj from the SDK that you downloaded, and your own project as well.
  3. Drag the FBConnect group to your project. When the prompt appears, make sure “Copy items into destination group’s folder” is not clicked.
  4. Go to Project\Edit Project Settings, and scroll down to “Search Paths\Header Search Paths.” Make sure “All Configurations” is sleeted, and add an entry to your search path that points to the src folder in the SDK – I used “../facebook-iphone-sdk/src”.
  5. Test that you have things working correctly, by importing the Facebook SDK headers. Just add “#import “FBConnect/FBConnect.h” to one of your header files and give it a compile to check everything is working!

Logging the User In

To log the user into Facebook, you need to set up a session for the user. Facebook sessions are managed by the FBSession object – and there can only be one session at a time. Therefore, you probably want to declare your FBSession somewhere that is easily accessible by any place in your code that may need to use it. In the sample project, I just have a single view controller, so I put it there, but for larger projects you should use a more central location.
To initialize your session, you need to give it some API keys so Facebook can distinguish between your application and someone else’s. This is often done in the viewDidLoad method where you want to start using Facebook, and there are two methods of doing this:
  • Hard code the API key and secret key into your application, and use the sessionForApplication:secret:delegate: method. This method is the easiest way, but someone motivated could reverse engineer your code and retrieve your secret key, and write an app to pose as your application.
  • The better way is to use the sessionForApplication:getSessionProxy:delegate method and pass a URL to a web server you control. At that URL, you can implement a service that uses Facebook Connect’s PHP API to call facebook.auth.getSession (with a hardcoded key there) and send the results back to the app. This method is higher security because to figure out your key, someone would need to have access to your web server.
Here’s what it looks like with the sessionForApplication:secret:delegate method:
static NSString* kApiKey = @"8fa673a06891cac667e55d690e27ecbb";
static NSString* kApiSecret = @"325a4c580253c7619313baad5712cc2a";
_session = [[FBSession sessionForApplication:kApiKey 
                                      secret:kApiSecret delegate:self] retain];
Next, it’s time to log the user in. The Facebook SDK makes it very easy to display a login dialog:
_loginDialog = [[FBLoginDialog alloc] init]; 
[_loginDialog show];
If you’d like to know if and when the user successfully logs in, all you have to do is implement the session:didLogin method in your FBSessionDelegate.
One of the nice things about sessions is they persist to disk automatically. After you set the API keys for your session, you can restore an old session by calling “[_session resume]“. This method will return YES or NO based on whether the session is valid or not, and it will also call session:didLogin on your delegate if the session is valid.

Posting to the User’s Wall

You can post to a user’s wall using the FBSteamDialog class, and a bit of markup. First, here’s an example:
FBStreamDialog* dialog = [[[FBStreamDialog alloc] init] autorelease];
dialog.userMessagePrompt = @"Enter your message:";
dialog.attachment = [NSString stringWithFormat:@"{\"name\":\"%@ got straight A's!\",\"href\":\"http://www.raywenderlich.com/\",\"caption\":\"%@ must have gotten real lucky this time!\",\"description\":\"\",\"media\":[{\"type\":\"image\",\"src\":\"http://www.raywenderlich.com/wp-content/themes/raywenderlich/images/logo.jpg\",\"href\":\"http://www.raywenderlich.com/\"}]}",
  _facebookName, _facebookName];
dialog.actionLinks = @"[{\"text\":\"Get MyGrades!\",\"href\":\"http://www.raywenderlich.com/\"}]";
[dialog show];
For simple posts, you should be able to tweak this sample pretty easily. If you want to do something more complex, refer to this great Facebook post attachment reference guide for all of the details.

Getting the User’s Facebook Name

If you integrate Facebook into your app, you’re probably going to want to get the user’s Facebook name, so that you can display who they are currently logged in as and let them log out, if nothing else.
The easiest way to do this is to use the same method used in the example provided by the Facebook SDK team – run a query against the Facebook database after a successful login.
NSString* fql = [NSString stringWithFormat:
    @"select uid,name from user where uid == %lld", _session.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"];
[[FBRequest requestWithDelegate:self] call:@"facebook.fql.query" params:params];
The results will come back in the request:didLoad method in your FBRequestDelegate:
- (void)request:(FBRequest*)request didLoad:(id)result {
 if ([request.method isEqualToString:@"facebook.fql.query"]) {
  NSArray* users = result;
  NSDictionary* user = [users objectAtIndex:0];
  NSString* name = [user objectForKey:@"name"];
  // Do something with the name!
 }
}

The Sample Project!

That’s all there is to it! So if you haven’t already, take a look at the example iPhone project showing how to make a Facebook post like the above. Feel free to play around (and even use the included API/Secret key) to test things out.

0 comments:

Post a Comment

 

Copyright @ 2013 PakTechClub.