简体   繁体   English

从函数返回数据(Swift)

[英]Returning Data From Function (Swift)

I am trying to return result and be able to access result array from this function. 我试图返回结果,并能够从此函数访问结果数组。 Everything is working in the function, however I cannot return anything or access results or any variable created inside the function from outside the closure. 一切都在函数中工作,但是我无法从闭包外部返回任何内容或访问结果或在函数内创建的任何变量。 I want to access result.valueForKey("id") from outside the closure. 我想从闭包外部访问result.valueForKey(“id”)。 How can I do that? 我怎样才能做到这一点?

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(facebookid)  // This doesn't work

    }
}



    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


        }
    })
}

Edit: I did change the code according to the 2 answers below but still I still can't get any data return on the viewDidLoad closure. 编辑:我确实根据下面的2个答案更改了代码但仍然无法在viewDidLoad闭包上获得任何数据返回。 * println(facebookid) doesn't return anything in the ViewDidLoad whereas it does inside the closure in function. * println(facebookid)不返回ViewDidLoad中的任何内容,而它在函数中的闭包内部。

You are creating the variables inside the closure meaning they can only be accessed inside. 您正在闭包内创建变量,这意味着它们只能在内部访问。

You need to create the variables outside of the function at the top of you class. 您需要在类顶部的函数外部创建变量。

for example 例如

 class YourClassName {

      var facebookid
      var username
      var userEmail


 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? String
        self.userName = result.valueForKey("name") as? String
        self.userEmail = result.valueForKey("email") as? String

    }
  })
 }
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {       
        if error != nil {
            print(error.localizedDescription)
            return
        }


                print("user loged in with facebook")
                if((FBSDKAccessToken.current()) != nil) {
                    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email, age_range, link, gender, locale, timezone, updated_time, verified"]).start(completionHandler: { (connection, result, error) -> Void in
                        if (error == nil){
                            print(result!)
                            print("Token: \((FBSDKAccessToken.current().tokenString)!)")
                            print("Token Expiration Date: \((FBSDKAccessToken.current().expirationDate)!)")
                        }
                    })
                }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM