0

基本上我想在函數(類SignUpPage.swift)中使用變量'userID'來將它稱爲HERE它在ViewController.swift類中。如何在類B中的類A的函數體內訪問變量的值?

我曾試圖使用戶ID全局變量

ref.child( 「用戶」)子(這裏).setValue。([userLN 「名」:userFN, 「姓」])也是,但這是不行的。 這裏是整個代碼:

class SignUpPage: UIViewController { 

var ref: FIRDatabaseReference! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    ref = FIRDatabase.database().reference() 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
} 
@IBOutlet weak var emailField: UITextField! 
@IBOutlet weak var passwordField: UITextField! 



@IBAction func signUpButton(_ sender: Any) { 


    FIRAuth.auth()?.createUser(withEmail: emailField.text!, password: passwordField.text!, completion: { (user, error) in 


     if error != nil{ 

      print(error!.localizedDescription) 
     } 

我想在ViewController.swift類中使用這個變量(用戶ID),這樣我可以節省名字,姓氏,EMAILID和密碼相同令牌下。

 let userID = user!.uid 

     let userEmail = self.emailField.text! 
     let userPassword = self.passwordField.text! 

     self.ref.child("Users").child(userID).setValue(["User Email": userEmail, "User Password": userPassword]) 
    }) 

} 

}

ViewController.swift類

class ViewController: UIViewController { 

var ref: FIRDatabaseReference! 

var ID = String() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    ref = FIRDatabase.database().reference() 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 
@IBOutlet weak var fnField: UITextField! 
@IBOutlet weak var lnField: UITextField! 

@IBAction func nextButton(_ sender: Any) { 



    let userFN: String = fnField.text! 
    let userLN: String = lnField.text! 

    ref.child("Users").child(**HERE**).setValue(["First Name": userFN, "Last Name": userLN]) 

} 

}

+1

你是如何從註冊的ViewController呈現視圖控制器? –

+0

看起來像'child()'接受一個字符串。 'userID'的類型是什麼? –

+0

@gkchristopher是啊,孩子()接受一個字符串 用戶ID爲String類型也 我遇到的問題是在訪問它的類 –

回答

0

據我所知,這是基本身份驗證邏輯,那麼你爲什麼不保存用戶id在UserDefaults,

let userID = user!.uid 
let userDefaults = UserDefaults.standard 
userDefaults.set(userID, forKey: "userID") 

比任何地方,當你想存儲的用戶ID,

let userDefaults = UserDefaults.standard 
let userID = userDefaults.string(forKey: "userID") 
ref.child("Users").child(userID).setValue(["First Name": userFN, "Last Name": userLN]) 
+0

它給出了這一行的錯誤 let userID = userDefault.string(forKey:「userID」)!作爲字符串 錯誤讀取 EXC_BAD_INSTRUCTION(code = EXC_I368_INVOP,subcode = 0x0) –

+0

應該讓userID = userDefault.string(forKey:「userID」)as!字符串 – ocanal

+0

我試過,但它給出了一個錯誤,說 - 從'字符串?'downcast。 to String只展開optionals –

相關問題