Firebase检查空值(Swift)

For*_*ded 4 ios 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)
        })
Run Code Online (Sandbox Code Playgroud)

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

 <null>
Run Code Online (Sandbox Code Playgroud)

我如何检查这个值?

 if profile == nil 
Run Code Online (Sandbox Code Playgroud)

不起作用

如果我做

let profile = snapshot.value as? String
Run Code Online (Sandbox Code Playgroud)

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

Erk*_*ken 26

利用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")
})
Run Code Online (Sandbox Code Playgroud)

.

这是另一个方便的例子,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"
        }
Run Code Online (Sandbox Code Playgroud)