检查Swift中的Firebase快照是否等于零 [英] Checking if Firebase snapshot is equal to nil in Swift

查看:151
本文介绍了检查Swift中的Firebase快照是否等于零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图查询Firebase,以检查是否有任何用户拥有等待:1,然后当快照返回时,我想查看它是否等于零。我试图做到这一点,但我用的方法是行不通的,如果快照不等于零,我只有某种输出。我已经添加了我目前拥有的代码和Firebase的JSON文本。

 导入UIKit 
导入Firebase
import spring

class GamesViewController:UIViewController {

let ref = Firebase(url:https://123test123.firebaseio.com)
var activityIndi​​cator: UIActivityIndi​​catorView = UIActivityIndi​​catorView()

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

let userRef = Firebase(url:https://123test123.firebaseio.com/users)
userRef.queryOrderedByChild(waiting)。queryEqualToValue(1)
.observeEventType (.ChildAdded,withBlock:{在
中快照print(snapshot.key)
如果snapshot.key == nil {
print(test2)
let userData = [等待:1]
let usersRef = self.ref.childByAppendingPath(users)
let hopperRef = u sersRef.childByAppendingPath(\(self.ref.authData.uid))

hopperRef.updateChildValues(userData,withCompletionBlock:{
(error:NSError ?, ref:Firebase!)在
if(error!= nil){
print(Data can not be saved。)
self.displayAlert(Oops!,message:我们一直无法得到你进入一个游戏,检查你有一个互联网连接。如果这个问题继续支持)
} 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)



})

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

$ 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) - >无效在

))))

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

func activityIndi​​catorFunction(){

activityIndi​​cator = UIActivityIndi​​catorView(frame:CGRectMake(0,0,100,100))
activityIndi​​cator.backgroundColor = UIColor(red:0.16,green:0.17,blue:0.21 ,alpha:1)
activityIndi​​cator.layer.cornerRadius = 6
activityIndi​​cator.center = self.view.center
activityIndi​​cator.hidesWhenStopped = true
activityIndi​​cator.activityIndi​​catorViewStyle = UIActivityIndi​​catorViewStyle.WhiteLarge
view.addSubview(activityIndi​​cator)
activityIndi​​cator.startAnimating()
UIApplication.sharedApplication()。beginIgnoringInteractionEvents()







JSON数据:

<$ p
$ {
68e42b7f-aea5-4c3f-b655-51a99cb05bb0:{
email:test1@test1.com,
username :test1,
等待


8503d5a8-fc4a-492b-9883-ec3664898b4f:{
email:test2@test2.com,
用户名:test2,
waiting:0
}
}


有一些事情在这里进行,但最重要的是你不能测试的孩子是否存在.ChildAdded

。如果你仔细想一想,这是有道理的:当一个孩子被添加到位置时,会引发 .ChildAdded 事件。如果没有添加子项,则不会引发该事件。

因此,如果要测试某个位置是否存在子项,则需要使用。价值。一旦你这样做,有各种方式来检测存在。这里有一个:

$ $ p $ $ $ $ $ $ ref.queryOrderedByChild(waiting)。queryEqualToValue(1)
.observeEventType(。值,withBlock {快照
print(snapshot.value)
if!snapshot.exists(){
print(test2)
}
}) ;


I am trying to query Firebase to check if any user that has waiting: "1" and then when the snapshot is returned I want to see whether it is equal to nil. I have attempted to do this but the method I have used does not work and I only have some sort of out put if the snapshot is not equal to nil. I have added the code I currently have and the JSON text from Firebase.

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 Data:

{
"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"
}
}

解决方案

There are a few things going on here, but the most important one is that you cannot test for the existence of children with .ChildAdded. That makes sense if you think about it: the .ChildAdded event is raised when a child is added to the location. If no child is added, the event won't be raised.

So if you want to test if a child exists at a location, you need to use .Value. Once you do that, there are various way to detect existence. Here's one:

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

这篇关于检查Swift中的Firebase快照是否等于零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆