Swift Retreive Firebase data

2019-01-25 22:42发布

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]()

3条回答
成全新的幸福
2楼-- · 2019-01-25 23:30

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楼-- · 2019-01-25 23:32

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!

            }

        })
查看更多
爷的心禁止访问
4楼-- · 2019-01-25 23:34

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)")
    }
})
查看更多
登录 后发表回答