Swift Retreive Firebase data

雨燕双飞 提交于 2020-01-10 03:14:18

问题


The following data in the Firebase Database:

{
  "schedule": {
      "Week 1": {
        "active": "true"
      },
      "Week 2": {
        "active": "true"
      },
      "Week 3": {
        "active": "false"
      },
      "Week 4": {
        "active": "true"
      },  
      ...
   }
}

I want to retrieve all the Weeks where the active is true only. I am setting the Firebase reference as such:

ref = FIRDatabase.database().reference(withPath: "Schedule")

and then doing the following:

ref.observeSingleEvent(of: .value, with: { snapshot in
        //
        print("Count: ", snapshot.childrenCount)

        for _ in snapshot.children {
                print("\(snapshot.value)")
        }

    })

Which produces the following output:

Optional({
      "Week 1" =     {
           active = 1;
       };
       "Week 2" =     {
           active = 1;
       };
       "Week 3" =     {
           active = 0;
       };
       "Week 4" =     {
           active = 1;
       };
       ...
}

Can someone please suggest how I can get just the weeks where active is set to true which needs to be loaded in an array of type string :

var weeksActive = [String]()

回答1:


For that you can use queryOrdered(byChild:) and queryEqual(toValue:) like this.

let ref = FIRDatabase.database().reference(withPath: "Schedule").queryOrdered(byChild: "active").queryEqual(toValue : true)

ref.observe(.value, with:{ (snapshot) in

    print("Count: ", snapshot.childrenCount)
    for child in snapshot.children {
        print("\((child as! FIRDataSnapshot).value)")
        //To get week you need to access key
        print("\((child as! FIRDataSnapshot).key)")
    }
})



回答2:


Here Is The Code

1) Create New Swift Page in The Name as Schedule.swift

2) Inside Schedule.swift Page Use The Below Code

import UIKit
class Schedule: NSObject
{
   var weeks: String?
   var active: String?
}

3) In ViewController.Swift Page or Other Page Use This Code

import UIKit
import Firebase
import FirebaseDatabase
class ViewController: UIViewController
{
    var ShceduleList = [Schedule]()
    var ref = FIRDatabaseReference!
    var refHandle: Uint!
    override func viewDidLoad()
    {
       super.viewDidLoad()
       ref = FIRDatabase.database().reference()
       self.FetchSchedule()
    }

    fun FetchSchedule()
    {
       refHandle = ref.child("schedule").observeEventType(.ChildAdded, withBlock: {(snapshot) in
          if let dictionary = snapshot.value as? [String: AnyObject]
          {
               let Schedule = Schedule()
               Schedule.setValuesForKeyWithDictionary(dictionary)
               self.ScheduleList.append(Schedule)
               dispatch_async(dispatch_get_main_queue(),{
                print("Schedule List: \(self.ScheduleList)")
               })
          } 
       })
    }
}

Here I Have Added Code Upto Appending Data's To Array You Just Need To Validate Values As Per Your Needs Before Appending To ScheduleList Array.




回答3:


This is the code for the problem mentioned above. First take the item value as FIRDatabaseSnapshot.value!. Then append it into weeksActive.

    ref.observeSingleEvent(of: .value, with: { snapshot in
            //
            print("Count: ", snapshot.childrenCount)

            for item in snapshot.children {
                    print("\(item as! FIRDataSnapshot).value)")
                   let week = item as! FIRDataSnapshot).value!

            }

        })


来源:https://stackoverflow.com/questions/41456785/swift-retreive-firebase-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!