在视图控制器之间传递FBSDK登录管理器结果

时间:2017-05-19 10:11:21

标签: ios swift fbsdk

我无法在视图控制器之间传输登录管理器结果, segue与按钮相关联,其标识符为s1。 我的设置是正确的。程序崩溃了绿色断点。 这是我的代码: 对于第一个VC:

import FBSDKLoginKit


class ViewController: UIViewController {

    var user_name: String?

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


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let fbLoginManager = FBSDKLoginManager()
        fbLoginManager.logIn(withReadPermissions: ["public_profile", "email"], from: self) { (result, error) in
            if let error = error {
                print("Failed to login: \(error.localizedDescription)")
                return
            }

            guard let accessToken = FBSDKAccessToken.current() else {
                print("Failed to get access token")
                return
            }

            let credential = FIRFacebookAuthProvider.credential(withAccessToken: accessToken.tokenString)


            FBSDKGraphRequest(graphPath: "/me", parameters: ["fields" : "email, id, locale"])
                .start(completionHandler:  { (connection, result, error) in
                    guard let result = result as? NSDictionary,
                        let user_name = result["user_name"] as? String,

                        else {

                            return
                    }

                    if(segue.identifier == "s1"){
                        if let v = segue.destination as? Re {


                            v.uname=user_name ?? ""



                            //v.uname = usr.text ?? ""
                        }
                    }              


                })


            // Perform login by calling Firebase APIs
            FIRAuth.auth()?.signIn(with: credential, completion: { (user, error) in
                if let error = error {
                    print("Login error: \(error.localizedDescription)")
                    let alertController = UIAlertController(title: "Login Error", message: error.localizedDescription, preferredStyle: .alert)

                    return
                }



            })

    }


    }


}

对于Re,下一个VC:

class Re: UIViewController {
    var uname: String?    
    @IBOutlet weak var l1: UILabel!
    var userfb: String?
    override func viewDidLoad() {
        super.viewDidLoad()
l1.text=uname
        // Do any additional setup after loading the view.
    }

}

1 个答案:

答案 0 :(得分:0)

您需要使用已在顶部声明的实例变量,如下所示。 现在,您已创建新的user_name并使用其他user_name

guard let result = result as? NSDictionary,
                        user_name = result["user_name"] as? String,// make change here

                        else {

                            return
                    }