Este documento foi atualizado.
A tradução para Português (Brasil) não foi concluída ainda.
Atualização em inglês: 26 de abr de 2022
Atualização em Português (Brasil): 3 de jul de 2020

Using the Graph API, iOS

Use the Graph API to get data in and out of Facebook's social graph.

This includes:

  • Fetching profile information to provide social context.
  • Fetching user information such as their likes or photos.
  • Publish posts (including videos or photos) to Facebook.
  • Publishing open graph stories to Facebook.
  • For more features, see the Graph API documentation.

This guide describes how you work with the Graph API using the Facebook SDK for iOS.

Prerequisites

Calling the Graph API requires someone to login to your app via Facebook and authorize permissions for your app.

For example, if you want to fetch someone's email address, your app must be authorized for the email permission. Be sure you are familiar with:

You also need your development environment set up for the iOS SDK and your app set up, see iOS, Getting Started Guide.

Fetch User Data

The SDK has two classes to work with the Graph API: FBSDKGraphRequest and FBSDKGraphRequestConnection which are similar to the Foundation framework's NSURLRequest and NSURLRequestConnection.

To use the FBSDKGraphRequest you provide the request with a specific Graph API endpoint. Then call FBSDKGraphRequestConnection to start the request and process its completion.

For convenience, the SDK has a startWithCompletionHandler: method on FBSDKGraphRequest to implicitly create a FBSDKGraphRequestConnection for you.

For example to fetch the profile information for the person currently logged into your app, make this call:

guard AccessToken.current != nil else { return }

let request = GraphRequest(graphPath: "me", parameters: [:])
request.start() { connection, result, error in
    if let result = result, error == nil {
        print("fetched user: \(result)")
    }
}

Batch Requests

In Graph API you can make batch requests in a single HTTP request, see Graph API, Making Batch Requests.

With the SDK, you can construct multiple requests and add them to the same FBSDKGraphRequestConnection instance. You should batch requests whenever possible to minimize network traffic.

For example here we request someone's Likes:

guard let token = AccessToken.current else { return }

if token.hasGranted("user_likes") {
    let meRequest = GraphRequest(graphPath: "me", parameters: [:])
    let likesRequest = GraphRequest(graphPath: "me/likes", parameters: [:])

    let connection = GraphRequestConnection()
    connection.add(meRequest) { connection, result, error in
        // Process the 'me' information
    }
    connection.add(likesRequest) { connection, result, error in
        // Process the 'likes' information
    }

    connection.start()
}

You can also specify batch parameters with the addRequest:completionHandler: overloads, which includes the ability to create a batch with dependent requests.

Share Photos and Videos

While you can always manually create FBSDKGraphRequests to work with the Graph API endpoints, the Facebook SDK for iOS simplifies sharing photos and videos with FBSDKShareKit.framework. For example, to share a photo:

let image: UIImage!
let content = SharePhotoContent()
content.photos = SharePhoto(image: image, isUserGenerated: true)

// Assuming self implements SharingDelegate
let dialog = ShareDialog(
    viewController: self,
    content: content,
    delegate: self
)
dialog.show()

You can also share videos using the FBSDKShareVideoContent type. See the Sharing on iOS.

Delete Objects

You can also delete objects that your app created by sending a DELETE request with the object's ID as the graph path.

For example, imagine you published a photo to a Page and received an ID of “1234”. The following code would delete the photo:

guard let token = AccessToken.current else { return }

if token.hasGranted("pages_manage_posts") {
    let request = GraphRequest(graphPath: "1234", parameters: [:], httpMethod: .delete)
    request.start { connection, result, error in
        if error == nil {
            print("Deleted photo")
        }
    }
}

Debugging Tips

You can experiment and test your requests with the Graph API Explorer.

You can also enable Graph API debug mode, see iOS SDK Troubleshooting, Graph API Debug Mode.