Adding a Facebook Like button to a website in HTML is extremely easy, thanks to Facebook’s Developer API. But it’s not as straightforward to implement it in an iOS App.
Thanks to UIWebViews we can create a small web view, perhaps 80 pixels tall, and load the Facebook Like button into it. Here’s how:
- (void)viewDidLoad { [super viewDidLoad]; // add Facebook Like button in web view NSURL *facebookLike = [NSURL URLWithString:@"http://www.facebook.com/plugins/like.php?href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fplugins%2F&width&layout=standard&action=like&show_faces=true&share=true&height=80&appId=186277158097599"]; [self.fbWebView loadRequest:[NSURLRequest requestWithURL:facebookLike]]; }
Now we’ll see something like this – and it’s even localised:
Here’s a Like Button Generator that will give you the URL to your own page (enter a URL, select Get Code, then choose URL):
– https://developers.facebook.com/docs/plugins/like-button/
The caveat is that it’s a UIWebView, and as such if users click on the Like Button, the “real” Facebook action happens inside your tiny web view (i.e. Facebook.com loads and prompts the user to login or sign up). Not really what we want.
Let’s fix it by simply placing a transparent UIButton on top of your web view, and hook the button up to an action:
- (IBAction)facebookLikeButton:(id)sender { // open the Facebook App and display our fanpage [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"fb://profile/429759140452016"]]; }
Now you can react however you see fit: open a URL in Safari, open the Facebook App, etc.
Another thing of note: since the button will be pulled in from Facebook.com, it will not be displayed when a user is not online. Check via UIWebViewDelegate and if the URL can’t be loaded present an image from your bundle instead.
- https://developers.facebook.com/docs/plugins/like-button/
- http://stackoverflow.com/questions/12125780/custom-url-scheme-for-new-facebook-ios-app
- http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
- https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebViewDelegate_Protocol/Reference/Reference.html