2016-02-28 58 views
3

我試圖查詢Firebase以檢查是否有waiting: "1"的用戶,然後當快照返回時,我想查看它是否等於零。我試圖做到這一點,但我使用的方法不起作用,如果快照不等於零,我只有某種輸出。我添加了我目前擁有的代碼和Firebase中的JSON文本。檢查Swift中的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數據:

{ 
"68e42b7f-aea5-4c3f-b655-51a99cb05bb0" : { 
    "email" : "[email protected]", 
    "username" : "test1", 
    "waiting" : "0" 
}, 
"8503d5a8-fc4a-492b-9883-ec3664898b4f" : { 
    "email" : "[email protected]", 
    "username" : "test2", 
    "waiting" : "0" 
} 
} 
+0

可能的答案。但請閱讀[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)(因爲我認爲你的問題可能是「如何檢測某個確定孩子是否存在?「)以及如何構建[最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)。如果你照顧兩者,我們會更容易幫助你。 –

回答

13

有幾件事情怎麼回事,但最重要的一個就是你不能測試.ChildAdded的兒童是否存在。如果你仔細考慮,這是有道理的:當孩子被添加到位置時,會引發.ChildAdded事件。如果沒有添加小孩,則不會提高活動。

因此,如果您想測試某個位置是否存在小孩,則需要使用.Value。一旦你這樣做,有各種方式來檢測存在。這裏有一個:下面

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

這個作品謝謝! :) –

4

檢查NSNull。這是觀察節點的代碼。查詢以同樣的方式工作。

這是一個完整的,經過測試的應用程序。要使用,修改字符串「現有的」一些你知道的路徑存在,比如您的用戶路徑和「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

+0

我剛試過這個,但它不工作...... @Jay –

+0

它確實工作!我用一個完整且經過測試的副本和我剛剛寫的粘貼應用程序更新了我的答案。如果你的代碼不工作,那麼還有其他的錯誤 - NSNull是要走的路! – Jay

+0

嗯,我所知道的是,我的工作似乎並不奏效,儘管您使用的查詢與我的不同......可能會有所作爲嗎? @Jay –