我想在FireBase中获取用户的地址和姓名,但是我找不到一种方法。
这是我最大的努力。这在Xcode中似乎很好,但当我按下按钮来检索值时,应用程序崩溃(线程1 exc_bad_指令(代码=exc_i386_invop子代码=0x0)

 ref?.child("users").child(user)
        .observeSingleEvent(of: .value, with: { (snapshot) in

            let userDict = snapshot.value as! [String: Any]

            let address = userDict["Address:"] as! String
            let name = userDict["Name:"] as! String
            print("Address: \(address)  Name: \(name)")})

最佳答案

就像评论中提到的@moritz,如果您强制打开(您告诉这些值不会是nil)并且如果您的某个值变成了nil,它将使应用程序崩溃。试试这个-

ref?.child("users").child(user).observeSingleEvent(of: .value, with: { snapshot in
  guard let userDict = snapshot.value as? [String: Any],
    let address = userDict["Address:"] as? String,
    let name = userDict["Name:"] as? String else {
      return
    }

  print("Address: \(address)  Name: \(name)")
})

如果您的NameAddress中的任何一个nil

关于swift - 从Firebase获取特定值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45530208/

10-14 16:59