Tutorial – Opening a Facebook page.
In todays connected world it is important to have a Facebook page so your user’s can connect and interact with you. In this tutorial we will look at adding a button that will open up a Facebook page within the Facebook app. If the user does not have the Facebook installed it will open up in Safari instead.
You can also view the tutorial on you’ve at:
Swift:
Objective-C:
To start of we create a blank project in Xcode. Select the storyboard and add a button to it.
From here in the top right select show the assistant editor , this shows our view controller. Select the button and control drag it into the code for the view controller. This will allow you to create an IBAction for the button. Create one as “likeusFB”.
Now the button is connected our code will go in this IBOutlet to open up the Facebook page.
We need two variables, one to store the Facebook page URL, and also the unique Facebook page numerical ID.
Before we make these variables get the Facebook page URL you want to link to, we will be using the Seemu Apps Facebook page.
Our URL is: https://www.facebook.com/SeemuApps
Along with the URL we need the unique Facebook page ID, this is used to open it the page up within the Facebook page app. To get this go to http://findmyfacebookid.com. Put your Facebook page URL in and it will return your ID. Ours is 719245588122387.
Now that we have these we make our two variables as follows:
var fbURLWeb: NSURL = NSURL(string: "https://www.facebook.com/SeemuApps")! var fbURLID: NSURL = NSURL(string: "fb://profile/719245588122387")!
NSURL *fbURLWeb = [[NSURL alloc] initWithString:@"https://www.facebook.com/SeemuApps"]; NSURL *fbURLId = [[NSURL alloc] initWithString:@"fb://profile/719245588122387"];
From here we now need a way to check if the Facebook app is installed. If so we open up the page in the app, otherwise we open it up in safari. To do this we use the following:
if(UIApplication.sharedApplication().canOpenURL(fbURLID)){ // FB installed UIApplication.sharedApplication().openURL(fbURLID) } else { // FB is not installed, open in safari UIApplication.sharedApplication().openURL(fbURLWeb) }
if ([[UIApplication sharedApplication] canOpenURL:fbURLId]) { // FB installed [[UIApplication sharedApplication] openURL:fbURLId]; } else { // FB is not installed, open in safari [[UIApplication sharedApplication] openURL:fbURLWeb]; }
Now you can run your code and test it. In the simulator since Facebook isn’t installed it will open the page up in safari. Otherwise if it is run on a iOS device with Facebook installed it will open up in the Facebook app.
Swift source code:
Objective-C source code: