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

问题描述:

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

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 
       } 



      }) 

    } 


    } 


} 

而对于重,未来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. 
    } 

} 

您需要使用您已在顶部如下声明的实例变量。 现在你有创造新user_name,并使用其它user_name

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

         else { 

          return 
        } 
+0

它给出了一个错误,预期让有条件 – dreamcode

+0

是它提示错误? – KKRocks

+0

类型的NSDictionary的值不解开,你的意思是使用?要么 ! – dreamcode