ios - Firebase 检查空值 (Swift)

标签 ios swift firebase

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

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/

相关文章:

ios - 如何在 swift 3 中生成 OAuth1 HMAC SHA1 签名

ios - 使用 Swift 3 #keyPath 引用 UIView 子类 .center

ios - 尝试用 iOS 的核心数据中的另一个替换现有的实体对象

ios - 无法在 objective-c AppDelegate.h 中导入 FirebaseMessaging

ios - 为什么减少间隔不会加快 iOS 计时器的执行速度?

ios - 如何仅使用 iOS 10 捕获 iOS Swift 3.0 中的崩溃

swift - 获取 Firebase 文档作为数组

ios - 在不使用 prepareforsegue 的情况下在 View Controller 之间传递数据

javascript - 访问另一个对象内部的对象属性

android - Firebase 无法将类型为 java.lang.String 的对象转换为类型