尝试读取我的数据库用户详细信息,将其打印为可选值

时间:2017-03-15 12:10:27

标签: ios swift firebase

尝试从firebase检索用户,并且不可能声明它返回一个可选值的错误,代码已经附加在下面。 我也在下面添加了调试器消息。

var ref = FIRDatabaseReference.init()

@IBOutlet weak var points: UILabel!
@IBOutlet weak var currentUser: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    ref = FIRDatabase.database().reference()
}

func setupProfile(){
    let uid = FIRAuth.auth()?.currentUser?.uid
    let ref = FIRDatabase.database().reference().child("users").child(uid!)
    ref.observeSingleEvent(of: .value, with: { snapshot in

    if let dictionary = snapshot.value as? [String: AnyObject] {

            let username1 = dictionary["username"] as! String
            print(username1)
            self.username.text = username1//Error is caused on this line EXC_BAD_Instruction
            //   ( code= EXC_I386_INVOP,subcode = 0x0)

        } 

    })
}
  

自动委派代理。要禁用代理,请在Info.plist Snap中将标志FirebaseAppDelegateProxyEnabled设置为NO(fpzfqMTapNel8F90q8bEO450eYg1){       email =“abcd@test.com”;
      points = 100;
      username = abcd;致命错误:在展开可选值(lldb)}

时意外发现nil

1 个答案:

答案 0 :(得分:0)

回答这个问题:代码格式错误,并且在快照中的nil值的情况下可以崩溃。即,这意味着,例如,您尝试访问snapshot.value中的密钥“username”(作为字典),但“用户名”密钥不存在。

以下是一些带有两个选项的建议代码

    let uid = FIRAuth.auth()?.currentUser?.uid
    let ref = FIRDatabase.database().reference().child("users").child(uid)
    ref.observeSingleEvent(of: .value, with: { snapshot in

         //make sure dict is available before proceeding
         if let dict = snapshot.value as? [String: AnyObject] {

              //this is a test in response to a comment
              let email = dictionary["email"] as! String
              print(email)
              self.user.text = email

              ///if you are sure the 'username' key will always exist (neve
              let username = dictionary["username"] as! String
              print(username)
              self.user.text = username

              //if you are unsure if the 'username' will exist or not, protect your code!
              if let username = dict["username"] as? String {
                   //do something with username
              }
         } 

    })

要同意这些意见,理解选项是使用Swift并保护代码(和用户)的关键。

还有其他选项可以保护您的代码,但请先尝试一下。