Facebook iOS Tutorial

With 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 8.3 and built for iOS 10.3

Project Setup

Open Xcode and create a new Single View Application.

Open Xcode and create a new Single View Application. For product name, use iOS10FacebookTutorial 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.

Storyboard Setup

Drag a Button from the Object Library to the top of the main view and give it a title of "Post to Facebook".  Select the Button and select the Align Auto Layout button on the bottom-right of the Storyboard. Select the "Horizontally in Container" checkbox and click "Add 1 Constraint".

Select the Button and click the Pin Auto Layout button on the bottom-right of the Storyboard. Pin the button to the top and click "Add 1 Constraint."

The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl-drag or right-click-drag from the Button to the ViewController class and create the following Action.

Go to the ViewController.swift file and import the social framework.

import Social

Next, implement the postToFacebook  method

@IBAction func postToFacebook(_ sender: Any) {
    // 1
    if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) {
        // 2
        if let controller = SLComposeViewController(forServiceType: SLServiceTypeFacebook) {
            // 3
            controller.setInitialText("Testing Posting to Facebook")
            // 4
            self.present(controller, animated:true, completion:nil)
        }
    }
    else {
        // 3
        print("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. Make sure a Facebook account is available in the settings -> Facebook section.

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