FaceBook Tutorial in iOS8 with Swift

With the introduction of the Social Framework it is possible to integrate your app with any supported social networking services. In this tutorial we use the social framework to send a post to Facebook. This tutorial is made with Xcode 6 and built for iOS8.

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftPostFacebookTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard. In Xcode 6 view controllers are now square by default, so that you can create one user interface for multiple devices. In iOS8 you can layout the Storyboard using constraints and size classes. Since this app is only going to be for the iPhone, you can disable size classes. In the File Inspector untick Use Size Classes.

Choose Keep size class data for: iPhone, and click Disable Size Classes.

Add a Button to the main view and give it a title of "Post to Facebook". The Storyboard should look like this.

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl + drag from the Button to the ViewController class and create the following Action

Next, implement the postToFacebook  method

@IBAction func postToFacebook(sender: UIButton) {
    // 1
    if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) { 
      // 2
      var controller = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
      // 3
        controller.setInitialText("Testing Posting to Facebook")
      // 4
        self.presentViewController(controller, animated:true, completion:nil)
    else {
      // 3
      println("no Facebook account found on device")
  1. We check if there is a Facebook account available on the device.
  2. We create a SLComposeViewController object, which embeds the Facebook Post screen and all functionality.
  3. The initial Facebook post text is set,
  4. The Facebook post View Controller  is presented.
  5. If the Facebook account isn't set up, we display an alert message at the console

Build and run the project and start posting to Facebook.

You can download the source code of the iOS8SwiftPostFacebookTutorial at the ioscreator repository on github