Swift Retreive Firebase数据
Firebase数据库中的以下数据:
{ "schedule": { "Week 1": { "active": "true" }, "Week 2": { "active": "true" }, "Week 3": { "active": "false" }, "Week 4": { "active": "true" }, ... } }
我想检索所有的活动只是真正的周。 我正在设置Firebase参考:
ref = FIRDatabase.database().reference(withPath: "Schedule")
然后执行以下操作:
ref.observeSingleEvent(of: .value, with: { snapshot in // print("Count: ", snapshot.childrenCount) for _ in snapshot.children { print("\(snapshot.value)") } })
其中产生以下输出:
Optional({ "Week 1" = { active = 1; }; "Week 2" = { active = 1; }; "Week 3" = { active = 0; }; "Week 4" = { active = 1; }; ... }
有人可以请build议如何才能得到活动被设置为真正的需要被装入一个stringtypes数组的星期几:
var weeksActive = [String]()
为此,你可以像这样使用queryOrdered(byChild:)
和queryEqual(toValue:)
queryOrdered(byChild:)
。
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)") } })
这是守则
1)在名称中创build新的Swift页面作为Schedule.swift
2)在Schedule.swift
页面内使用下面的代码
import UIKit class Schedule: NSObject { var weeks: String? var active: String? }
3)在ViewController.Swift
页面或其他页面使用此代码
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)") }) } }) } }
在这里,我已经添加了代码Upto追加数据的数组您只需要根据您的需要validation值附加到ScheduleList数组之前。
这是上面提到的问题的代码。 首先将项目值作为FIRDatabaseSnapshot.value !. 然后将其附加到周活动。
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! } })