1

如果我直接在 viewController 上实现以下功能,一切正常。(这不完整,但它适用于图片)

func getFBData() {

if((FBSDKAccessToken.currentAccessToken()) != nil){
    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, email, first_name, last_name, picture"]).startWithCompletionHandler({ (connection, result, error) -> Void in
        if (error == nil){
            let email = result.valueForKey("email") as? String
            let fbid = result.valueForKey("id") as! String
            let fname = result.valueForKey("first_name") as! String
            let lname = result.valueForKey("last_name") as! String
            let facebookProfileUrl = "http://graph.facebook.com/\(fbid)/picture?type=large"

            let url = NSURL(string: facebookProfileUrl)

            if let data = NSData(contentsOfURL: url!) {
                self.imgProfile.image = UIImage(data: data)
            }
        }
    })
}

}

但相反,我试图将所有与 Facebook 相关的东西分开放在FacebookController.swift类中。

class func getUserData() -> [String: String] {

    var dict: [String: String]?
    let token = FBSDKAccessToken.currentAccessToken()
    let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, email, name, first_name, last_name, picture"])

    if((token) != nil) {
        graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
            if (error == nil) {

                let fbid = result.valueForKey("id") as! String
                let name = result.valueForKey("name") as? String
                let fname = result.valueForKey("first_name") as! String
                let lname = result.valueForKey("last_name") as! String
                let email = result.valueForKey("email") as? String
                let pictureURL = "http://graph.facebook.com/\(fbid)/picture?type=large"

                dict = ["id": fbid, "name": name!, "fname": fname, "lname": lname, "email": email!, "picture": pictureURL]
                print(dict)
            } else {
                print("ok")
                print("\(error)")
            }

        })

    }
    return dict!
}

用户已登录并授予所有权限,但是当我尝试调用FacebookController(). getUserData()它返回 dict,它是 nil。我已经认为这是因为从不调用completionHandlergraphRequest

有人可以帮忙吗?

4

0 回答 0