使用Swift在iOS SDK中处理Facebook Graph API

Lir*_*ira 5 facebook-graph-api facebook-ios-sdk swift

我只是想从Facebook的Graph API请求数据,例如获取当前用户的基本信息.

Objective-C文档是: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   
  }
}];
Run Code Online (Sandbox Code Playgroud)

还没有Swift文档,我对类型为"id"的"result"参数感到困惑.

vac*_*ama 10

它看起来像result包含字典,但它可能是nil.在Swift中,它的类型将映射到AnyObject?.

所以,Swift你可以做一些事情:

// 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!)")
    }
}
Run Code Online (Sandbox Code Playgroud)

这可以简化一下:

let resultdict = result as? NSDictionary
if let idvalue = resultdict?["id"] as? String {
    println("the id value is \(idvalue)")
}
Run Code Online (Sandbox Code Playgroud)

  • 它工作,谢谢!我认为现在这是唯一一个第一个iOS语言是Swift的人在线的FB SDK doc. (2认同)