Graph API

分类目录: Swift SDK

Graph API

The API for sending graph requests has been rebuilt from the ground-up for Swift. Now it follows the best practices outlined in the Using the Graph API iOS documentation.

You can still send requests in the same way as you do with the existing iOS SDK. The following code example demonstrates how to use the Graph API to get a list of likes for the current user using the previous/classic method.

import FacebookCore

// Requires user_likes permission to be granted.
let connection = GraphRequestConnection()
connection.add(GraphRequest(graphPath: "me/likes")) { 
  (response: NSHTTPURLResponse?, result: GraphRequestResult<GraphResponse>) in
  // Process error or results here.
}
connection.start()

For more information on user permissions, see Permissions with Facebook Login.

The current approach to Graph API requests uses a custom type-safe API for the requests. This allows you to reason about the types of your graph API requests more accurately, and provides a clean API for consuming this data.

The following code example demonstrates the same Graph API query as the previous example, but does so using the type-safe approach.

import FacebookCore

struct UserLikesRequest: GraphRequestProtocol {
  struct Response: GraphResponseProtocol {
    init(rawResponse: AnyObject?) {
      // Decode JSON from rawResponse into other properties here.
    }
  }

  public let graphPath = "me/likes"
  public let parameters: [String:AnyObject]? = []
  public let authenticationToken: AccessToken = AccessToken.current
  public let httpMethod: GraphRequestHTTPMethod = .GET
  public let apiVersion = "GRAPH_API_VERSION"
}

// Requires user_likes permission to be granted.
let connection = GraphRequestConnection()
connection.add(UserLikesRequest()) { (response: NSHTTPURLResponse?, 
  result: GraphRequestResult<UserLikesRequest.Response>) in
  // Process error or results here.
}
connection.start()