Sort Firebase data by date - ios

I keep getting this error and I failed to debug:
Could not cast value of type 'FIRDatabaseQuery' (0x10b32b700) to 'FIRDatabaseReference' (0x10b32b520).
That error comes from a regular .swift file with:
import Foundation
import Firebase
import FirebaseDatabase
let DB_BASE = FIRDatabase.database().reference()
class DataService {
static let ds = DataService()
private var _REF_BASE = DB_BASE
private var _REF_INCOMES = DB_BASE.child("incomes").queryOrdered(byChild: "date")
private var _REF_USERS = DB_BASE.child("users")
var REF_BASE: FIRDatabaseReference {
return _REF_BASE
}
var REF_INCOMES: FIRDatabaseReference {
return _REF_INCOMES as! FIRDatabaseReference // Thread 1: signal SIGABRT
}
[...]
}
Before adding .queryOrdered(byChild: "date") and as! FIRDatabaseReference everything worked except that I could not get a sort by date.
class IncomeFeedVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var incomes = [Income]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
DataService.ds.REF_INCOMES.observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
if let incomeDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let income = Income(incomeId: key, incomeData: incomeDict)
self.incomes.append(income)
}
}
}
self.tableView.reloadData()
})
}
[...]
}
What am I after? To start, I need to sort my date then work towards my Sketch view:
How do you sort? Few tutorials I see uses CoreData. Im using Firebase.

your private var _REF_INCOMES is FIRDatabaseQuery not FIRDatabaseReference ..
var REF_INCOMES: FIRDatabaseQuery {
return _REF_INCOMES
}
And please check this Q&A to sort your array

Related

How to access Array created in closure?

I created scheduleDict1 and inserted it into scheduleArray1. I can only get the closure to "see" scheduleArray1 when it is declared in the closure as in the code now. However, I can't access scheduleArray1 anywhere other than the closure.
I have tried declaring the scheduleArray1 in the MainViewController class instead of the closure but it will not be seen inside the closure!
import UIKit
import Firebase
class MainViewController: UITableViewController {
// var scheduleArray1 = [[String: String]]()
var scheduleDict = [String: Any]()
override func viewDidLoad() {
super.viewDidLoad()
retrieveSchedule()
}
func retrieveSchedule(){
let ref = Database.database().reference(withPath: "squadrons/vt-9/2019-04-02/events/")
ref.observe(.value) { (snapshot) in
var scheduleArray1 = [[String: String]]()
var count = 0
let enumerator = snapshot.children
while let rest = enumerator.nextObject() {
let refToPost = Database.database().reference(withPath: "squadrons/vt-9/2019-04-02/events/" + "\(count)")
refToPost.observe(.value, with: { (snapshot) in
// let data = snapshot.children
let scheduleDict1 = snapshot.value as! [String: String]
scheduleArray1.append(scheduleDict1)
// self.print(scheduleArray1)
})
count += 1
}
}
}
}

Swift Firebase completion handler not working, not fetching Data

I have my function here which is supposed to pull all the locations under the child "launch" in my database.
import UIKit
import Firebase
import FirebaseDatabase
class SearchSelectVC: UIViewController, UIPickerViewDelegate , UIPickerViewDataSource{
#IBOutlet weak var locationPicker: UIPickerView!
#IBOutlet weak var datePicker: UIPickerView!
#IBOutlet weak var locationLB: UILabel!
#IBOutlet weak var dateLB: UILabel!
var locData: [String] = [String]()
var dateData : [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
initPickers()
getloc(onCompletion: { (data) in
print(data)
self.locData = (data)
})
}
func getDate(onCompletion: #escaping ([String]) -> ()) {
var data : [String] = []
let selectedLoc = locationLB.text
var dateRef: DatabaseReference!
dateRef = Database.database().reference().child("launch").child((selectedLoc)!)
dateRef.observe(.value) { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
data.append(key)
print("date = \(key)")
//print(data)
}
onCompletion(data)
}
}
func getLoc(onCompletion: #escaping ([String]) -> Void){
print("here3")
var data : [String] = []
var locRef: DatabaseReference!
locRef = Database.database().reference()
print("here4")
locRef.child("launch").observe(.value) { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
print(snap)
print(key)
data.append(key)
print("location = \(key)")
//print(data)
}
onCompletion(data)
}
}
func initPickers(){
locationPicker.delegate = self
locationPicker.dataSource = self
datePicker.delegate = self
datePicker.dataSource = self
}
}
None of the "here" statements get printed out, neither the snapshot of key or the data which is being collected. Im not really sure whats wrong with my code. Here is a picture of my database
Thanks!

how do i get the value of self into the normal Variable

how can i get the value of self.valve1 from function readFireBaseData() into the function viewDidload() ??? i always get the set value of "valve1" which i set at the begining of the program. Hope someone can help me.
import UIKit
import FirebaseDatabase
import Firebase
class ValveViewController: UIViewController {
var valve1 = "OFF"
#IBOutlet var valveOne: UILabel!
override func viewDidLoad() {
readFirebaseData() //run the function readFireBaseData
let toggle = view.viewWithTag(1) as! UISwitch
if valve1 == "ON"
{
toggle.setOn(true, animated: true)
}else
{
toggle.setOn(false, animated: true)
}
super.viewDidLoad()
}//END of viewDidLoad
func readFirebaseData(){
var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("switchValve").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
self.valve1 = value?["valveOne"] as? String ?? ""
})
}//End of readFireBaseData
}//End of ViewController

How to retrieve data from Firebase to TableViewCell

I'm working on simple program - I create objects of products and then I count their calories.
I want to get all my product in TableViewController
I've created a method, allowing me to save data properly in Firebase, but I got stuck while retrieving them to cell. I got no mistakes, but I don't have any results as well
import UIKit
import Firebase
class MainTableViewController: UITableViewController {
var products = [Products]()
override func viewDidLoad() {
super.viewDidLoad()
DataService.dataService.PRODUCT_BASE.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.products = []
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let product = Products(key: key, dictionary: postDictionary)
}
}
}
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return products.count
}
override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell") as! UITableViewCell?
let ProductItem = products[indexPath.row]
cell?.textLabel?.text = ProductItem.productName
cell?.detailTextLabel?.text = String(ProductItem.productCalories)
return cell!
}
This is my DataService file:
import Foundation
import Firebase
let URL_BASE = FIRDatabase.database().reference()
class DataService {
static let dataService = DataService()
private var _REF_BASE = URL_BASE
private var _USER_BASE = URL_BASE.child("users")
private var _PRODUCЕ_BASE = URL_BASE.child("products")
var REF_BASE: FIRDatabaseReference {
return _REF_BASE
}
var USER_BASE: FIRDatabaseReference {
return _USER_BASE
}
var PRODUCT_BASE: FIRDatabaseReference {
return _PRODUCЕ_BASE
}
var CURRENT_USER_REF: FIRDatabaseReference {
let userID = NSUserDefaults.standardUserDefaults().valueForKey("uid") as! String
let currentUser = URL_BASE.child("users").child(userID)
return currentUser
}
func CreateNewProduct(product: Dictionary<String, AnyObject>) {
let ProductNewRef = DataService.dataService.PRODUCT_BASE.childByAutoId()
ProductNewRef.setValue(product)
}
I can't get what I'm doing wrong. All products are represented as a dictionary.
import Foundation
import Firebase
class Products {
private var _productName: String!
private var _productCalories: Int!
var productName: String {
return _productName
}
var productCalories: Int {
return _productCalories
}
init(key: String, dictionary: Dictionary<String, AnyObject>) {
if let calories = dictionary["calories"] as? Int {
self._productCalories = calories
}
if let name = dictionary["name"] as? String {
self._productName = name
}
}
}
You intilized the
var products = [Products]()
But not adding any items from firebase callback
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let product = Products(key: key, dictionary: postDictionary)
}
please add self.products.append(product)
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let product = Products(key: key, dictionary: postDictionary)
self.products.append(product)
}

TableView data not showing after updating Firebase code (Swift 2, Firebase 3.x)

Have been updating my project to the newest firebase code and am now running into an issue.
Yesterday my app was working fine w/ the updates I implemented and all of the sudden my tableView is no longer displaying data and it's not even printing the data in my console.
Here's my code:
import UIKit
import Firebase
import MGSwipeTableCell
class FeedVCViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var posts = [Post]()
static var imageCache = NSCache()
var isPostHidden = false
var likeRef: FIRDatabaseReference!
var dislikeRef: FIRDatabaseReference!
var postRef: FIRDatabaseReference!
var postLiked = false
var postDisliked = false
private var _post: Post?
var post: Post? {
return _post
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 38, height: 38))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "unilogo2Whtie")
imageView.image = image
navigationItem.titleView = imageView
DataService.ds.REF_POSTS.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.posts = []
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
print("SNAP: \(snap)")
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, dictionary: postDict)
self.posts.append(post)
}
}
}
self.tableView.reloadData()
})
// Do any additional setup after loading the view.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
I must have done something wrong in the update I'm assuming, can anyone help?
I'm surprised you're not getting an error on the following lines:
var likeRef: FIRDatabaseReference!
var dislikeRef: FIRDatabaseReference!
var postRef: FIRDatabaseReference!
For me, I had to add the following line below import Firebase in order not to get an error when declaring the database reference:
import FirebaseDatabase
Then in your viewDidLoad method you need to add the reference to your database
likeRef = FIRDatabase.database().reference()
However, with this new version of Firebase, you don't need a separate reference for likeRef, dislikeRef and postRef. You can make just one main reference and then access the child of the reference for those details.

Resources