在Swift中检查Firebase快照是否等于nil

时间:2016-02-28 12:44:36

标签: json swift firebase arc4random

我正在尝试查询Firebase以检查是否有任何用户waiting: "1"然后返回快照时我想查看它是否等于nil。我试图这样做,但我使用的方法不起作用,如果快照不等于nil,我只有一些输出。我添加了我当前拥有的代码和Firebase中的JSON文本。

import UIKit
import Firebase
import Spring

class GamesViewController: UIViewController {

let ref = Firebase(url: "https://123test123.firebaseio.com")
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()   

@IBAction func StartGamePressed(sender: AnyObject) {
    print("test1")
    var peopleWaiting: [String] = []

    let userRef = Firebase(url:"https://123test123.firebaseio.com/users")
    userRef.queryOrderedByChild("waiting").queryEqualToValue("1")
        .observeEventType(.ChildAdded, withBlock: { snapshot in
            print(snapshot.key)
            if snapshot.key == nil {
                print("test2")
                let userData = ["waiting": "1"]
                let usersRef = self.ref.childByAppendingPath("users")
                let hopperRef = usersRef.childByAppendingPath("\(self.ref.authData.uid)")

                hopperRef.updateChildValues(userData, withCompletionBlock: {
                    (error:NSError?, ref:Firebase!) in
                    if (error != nil) {
                        print("Data could not be saved.")
                        self.displayAlert("Oops!", message: "We have been unable to get you into a game, check you have an internet conection. If this problem carries on contect support")
                    } else {
                        print("Data saved successfully!")
                        let storyboard = UIStoryboard(name: "Main", bundle: nil)
                        let Home : UIViewController = storyboard.instantiateViewControllerWithIdentifier("continueToGame")
                        self.presentViewController(Home, animated: true, completion: nil)

                    }

                })


            } else {
                var randomUID: String
                peopleWaiting.append(snapshot.key)
                let randomIndex = Int(arc4random_uniform(UInt32(peopleWaiting.count)))
                randomUID = peopleWaiting[randomIndex]
                print(randomUID)
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let Home : UIViewController = storyboard.instantiateViewControllerWithIdentifier("continueToGame")
                self.presentViewController(Home, animated: true, completion: nil)

            }
        })
}

func displayAlert(title: String, message: String){

    let formEmpty = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    formEmpty.addAction((UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in

    })))

    self.presentViewController(formEmpty, animated: true, completion: nil)
}

func activityIndicatorFunction(){

    activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 100, 100))
    activityIndicator.backgroundColor = UIColor(red:0.16, green:0.17, blue:0.21, alpha:1)
    activityIndicator.layer.cornerRadius = 6
    activityIndicator.center = self.view.center
    activityIndicator.hidesWhenStopped = true
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
    view.addSubview(activityIndicator)
    activityIndicator.startAnimating()
    UIApplication.sharedApplication().beginIgnoringInteractionEvents()

}


}

JSON数据:

{
"68e42b7f-aea5-4c3f-b655-51a99cb05bb0" : {
  "email" : "test1@test1.com",
  "username" : "test1",
  "waiting" : "0"
},
"8503d5a8-fc4a-492b-9883-ec3664898b4f" : {
  "email" : "test2@test2.com",
  "username" : "test2",
  "waiting" : "0"
}
}

2 个答案:

答案 0 :(得分:15)

这里有一些事情,但最重要的是你不能用.ChildAdded来测试孩子的存在。如果您考虑一下,这是有道理的:当孩子被添加到该位置时,会引发.ChildAdded事件。如果没有添加子项,则不会引发该事件。

因此,如果您想测试某个地点是否存在儿童,则需要使用.Value。一旦你这样做,有各种方法来检测存在。这是一个:

ref.queryOrderedByChild("waiting").queryEqualToValue("1")
   .observeEventType(.Value, withBlock: { snapshot in
       print(snapshot.value)
       if !snapshot.exists() {
           print("test2")
       }
   });

答案 1 :(得分:4)

检查NSNull。这是观察节点的代码。查询的工作方式大致相同。

这是一个完整且经过测试的应用。要使用,请将字符串'existing'更改为您知道存在的某个路径,例如您的用户路径和'notexisting'到某个不存在的路径

    let myRootRef = Firebase(url:"https://your-app.firebaseio.com")
    let existingRef = myRootRef.childByAppendingPath("existing")
    let notExistingRef = myRootRef.childByAppendingPath("notexisting")

    existingRef.observeEventType(.Value, withBlock: { snapshot in

        if snapshot.value is NSNull {
            print("This path was null!")
        } else {
            print("This path exists")
        }

    })

    notExistingRef.observeEventType(.Value, withBlock: { snapshot in

        if snapshot.value is NSNull {
            print("This path was null!")
        } else {
            print("This path exists")
        }

    })

请注意,通过使用.Value,将保证返回结果并且块将始终触发。如果您的代码使用.ChildAdded,那么该块只会在子项存在时触发。

另外,请检查以确保数据在firebase中的显示方式。

users
   user_0
     waiting: 1

如果不同于

users
   user_0
     waiting: "1"

请注意,“1”与1不同。