Firebase检查空值(Swift)

我正在运行下面的代码,以查看打开应用程序的用户是否已登录,然后检查他们是否已设置配置文件。 我在检查配置文件检查返回的空值时遇到问题

override func viewDidLoad() { super.viewDidLoad() //Check to see if user is already logged in //by checking Firebase to see if authData is not nil if ref.authData != nil { //If user is already logged in, get their uid. //Then check Firebase to see if the uid already has a profile set up let uid = ref.authData.uid ref.queryOrderedByChild("uid").queryEqualToValue(uid).observeSingleEventOfType(.Value, withBlock: { snapshot in let profile = snapshot.value print(profile) }) 

在我打印(个人资料)的最后一行,我要么获取个人资料信息,要么

   

我如何检查这个值?

  if profile == nil 

不起作用

如果我做

 let profile = snapshot.value as? String 

首先,即使有snapshot.value,它总是返回nil

利用exists()方法确定快照是否包含值。 要使用您的示例:

 let uid = ref.authData.uid ref.queryOrderedByChild("uid").queryEqualToValue(uid) .observeSingleEventOfType(.Value, withBlock: { snapshot in guard snapshot.exists() else{ print("User doesn't exist") return } print("User \(snapshot.value) exists") }) 

这是另一个方便的例子,Swift4

  let path = "userInfo/" + id + "/followers/" + rowId let ref = Database.database().reference(withPath: path) ref.observe(.value) { (snapshot) in let following: Bool = snapshot.exists() icon = yesWeAreFollowing ? "tick" : "cross" } 

您可能想要探索另一个选项:因为您知道用户的uid以及该用户的路径,所以没有理由进行查询。 查询会在您知道路径的情况下增加不必要的开销。

例如

 users uid_0 name: "some name" address: "some address" 

通过值观察有问题的节点要好得多,如果不存在则返回null

 ref = "your-app/users/uid_0" ref.observeEventType(.Value, withBlock: { snapshot in if snapshot.value is NSNull { print("This path was null!") } else { print("This path exists") } }) 

如果你以其他方式存储它; 也许

 random_node_id uid: their_uid name: "some name" 

然后查询将按顺序排列,就像这样

 ref.queryOrderedByChild("uid").queryEqualToValue(their_uid) .observeEventType(.Value, withBlock: { snapshot in if snapshot.exists() { print("you found it!") } });