如何准备segue swift变量登录用户名

时间:2018-04-16 18:18:21

标签: ios swift

在导航控制器中,从我的LoginPage,我试图将用户名传递给我的应用程序MainViewController,并将其显示在标签中。当然用户名必须是一个变量,但到目前为止只是成功传递和显示静态文本,例如Arthur Dent

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "OpenPVOapp" {
        let vc = segue.destination as! MainViewController
        vc.userName = "Arthur Dent"
    }
}
// LOGIN with FACEBOOK
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
  if error != nil{
      self.lblStatus.text = error.localizedDescription
  }else if result.isCancelled{
    self.lblStatus.text = "user cancelled Login"
  }else{
  //successful Login
  // GET FACEBOOK INFO
    let params = ["fields" : "email, name"]
    let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: params)
    _ = graphRequest?.start(completionHandler: { (connection, result, error) in
      if error != nil {
        print(error!.localizedDescription)
        return
      }
      if let result = result as? [String:Any]{
        guard let email = result["email"] as? String else {
          return
        }
        guard let username = result["name"] as? String else {
          return
        }
        self.lblStatus.numberOfLines = 0
        self.lblStatus.text = "CURRENT USER: " + username + "\n " + email
      }
    })
  // END GET FACEBOOK INFO
    performSegue(withIdentifier: "OpenApp", sender: nil)
  }
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
  self.lblStatus.text = "user logged out"
}

在MainViewController中:

var userName:String = "Anonymous"
@IBOutlet weak var userNameLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    userNameLabel?.text = "Current User: " + userName
}

当然,使用"Arthur Dent"生成替换username!使用未解析的标识符username

但是,将func prepare(for segue:...块移动到FBSDKGraphRequest:

self.lblStatus.text = "CURRENT USER: " + username + "\n " + email
        func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          if segue.identifier == "Openapp" {
            let vc = segue.destination as! MainViewController
            vc.userName = username
          }
        }

在MainViewController userNameLabel中显示Current User: Anonymous

所以我的问题是如果可能的话,如何配置这样的导航控制器prepare(for segue:...设置以传递变量username文本?

1 个答案:

答案 0 :(得分:0)

试试这个:

self.lblStatus.text = "CURRENT USER: " + username + "\n " + email
// just after the above line paste this
performSegue(withIdentifier: "OpenApp", sender: username)

现在在prepareForSegue中获取此用户名:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "OpenPVOapp" {
        let vc = segue.destination as! MainViewController
        vc.userName = sender as? String ?? ""
    } 
}