gpt4 book ai didi

ios - Firebase 检查空值 (Swift)

转载 作者:搜寻专家 更新时间:2023-10-31 08:09:12 24 4
gpt4 key购买 nike

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

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)
})

在我打印(配置文件)时的最后一行,我要么获取配置文件信息,要么

 <null>

我如何检查这个值?

 if profile == nil 

不工作

如果我这样做

let profile = snapshot.value as? String

首先,然后它总是返回nil,即使有一个snapshot.value

最佳答案

利用 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"
}

关于ios - Firebase 检查空值 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35882630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com