将函数中的数据返回到全局变量(Swift)

时间:2015-04-10 16:24:22

标签: ios swift facebook-sdk-4.0

我正在尝试返回结果并能够从此函数访问结果数组。一切都在函数中工作,但是我无法从闭包外部返回任何内容或访问结果或在函数内创建的任何变量。我想从闭包外部(在ViewDidLoad中)访问result.valueForKey(" id")。我怎样才能做到这一点? (请参阅"这适用于"以及"这不起作用"部分......

 class ViewController: UIViewController, FBSDKLoginButtonDelegate {

 var facebookid: NSString = ""
 var username: NSString = ""
 var userEmail:NSString = ""

 override func viewDidLoad() {
  super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

if (FBSDKAccessToken.currentAccessToken() == nil)
{
    let loginView : FBSDKLoginButton = FBSDKLoginButton()
    self.view.addSubview(loginView)
    loginView.center = self.view.center
    loginView.readPermissions = ["public_profile"]
    loginView.delegate = self

} else {

    returnUserData()

    println("test") // This works (gets printed)
    println(facebookid)  // This doesn't work (not even nil)
    println(self.username) // This doesn't work either (not even nil)

  }
}



func returnUserData()
{

let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

    if ((error) != nil)
    {
        // Process error
        println("Error: \(error)")
    }
    else
    {

        self.facebookid = result.valueForKey("id") as NSString!
        self.username = result.valueForKey("name") as NSString!
        self.userEmail = result.valueForKey("email") as NSString!
        println(result) // This works
        println(facebookid) // This works


    }
})
}

1 个答案:

答案 0 :(得分:0)

原因是您在returnUserData中的请求不是同步函数,因此在您对这些数据调用println()后它会更新您的数据。您应该在iOS中阅读有关MultiThreading的更多信息。

returnUserData()  //it calls returnUserData() to update your facebookid & self.username. However, in `returnUserData`, it use `FBSDKGraphRequest` to get facebook datas. As FBSDKGraphRequest retrieve datas from internet connection (and it takes time to finish), it is designed to retrieve datas in async, to avoid blocking your function.

//So, you risk to finish your returnUserData function before the process of FBSDKGraphRequest is terminated (and the completionHandler is called to update your data). 

println("test") // This works (gets printed)
println(facebookid)  // This doesn't work (not even nil) //this is called before your completionHandler is invoked, you don't have new data
println(self.username) // This doesn't work either (not even nil) //this is called before your completionHandler is invoked too, you don't have new data.

要解决此问题,您应该在facebookid

中使用self.usernamecompletionHandler的新值开展工作