Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Facebook Graph API result in iOS SDK with Swift

I just want to request data from Facebook's Graph API, e.g. get the current user's basic info.

The Objective-C doc is: https://developers.facebook.com/docs/ios/graph#userinfo

[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
  if (!error) {

    /* My question: How do I read the contents of "result" in Swift? */

    // Success! Include your code to handle the results here
    NSLog(@"user info: %@", result);
  } else {
    // An error occurred, we need to handle the error
    // See: https://developers.facebook.com/docs/ios/errors   
  }
}];

There's no Swift doc yet, and I'm confused about the "result" parameter whose type is "id".

like image 508
Liron Shapira Avatar asked Jun 15 '14 01:06

Liron Shapira


1 Answers

It looks like result contains a dictionary, but it may be nil. In Swift, its type will map to AnyObject?.

So, in Swift, you could do something like:

// Cast result to optional dictionary type
let resultdict = result as? NSDictionary

if resultdict != nil {
    // Extract a value from the dictionary
    let idval = resultdict!["id"] as? String
    if idval != nil {
        println("the id is \(idval!)")
    }
}

This can be simplified a bit:

let resultdict = result as? NSDictionary
if let idvalue = resultdict?["id"] as? String {
    println("the id value is \(idvalue)")
}
like image 176
vacawama Avatar answered Sep 29 '22 20:09

vacawama