iOS Firebase - print(snapshot.value) to TableView - ios

I am connecting my firebase database with my Xcode Project. I have successfully used the print(snapshot.value) to print my snapshot of the database into the console. However, I am struggling to print my snapshot of data into the TableView. Thank you.
Here is my code :
import UIKit
import FirebaseDatabase
class ViewController: UITableViewController {
#IBOutlet var cosmos: UITextView!
#IBOutlet var gallonsTXT: UITableView!
#IBOutlet var tables: UITableView!
#IBOutlet var Finale: UILabel!
var ref:DatabaseReference?
var databaseHandle:DatabaseHandle?
var postData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
gallonsTXT.delegate = self
gallonsTXT.dataSource = self
ref = Database.database().reference()
databaseHandle = ref?.child("Total gallons:").observe(.childAdded, with: { (snapshot) in
print(snapshot.value)
let post = snapshot.value as? String
if let actualPost = post {
self.postData.append(actualPost)
self.tableView.reloadData()
}
})
// Do any additional setup after loading the view, typic ally from a nib.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell")
cell?.textLabel?.text = postData[indexPath.row]
return cell!
}
}

Adjust your view did load to the following. You must declare a dictionary in order to properly read and use data from Firebase.
override func viewDidLoad() {
super.viewDidLoad()
gallonsTXT.delegate = self
gallonsTXT.dataSource = self
ref = Database.database().reference()
databaseHandle = ref?.child("Total gallons:").observe(.childAdded, with: { (snapshot) in
print(snapshot.value)
if let dict = snapshot.value as? [String: Any] {
let post = dict["your data key"] as! String
self.postData.append(actualPost)
self.tableView.reloadData()
}
})
// Do any additional setup after loading the view, typic ally from a nib.
}
If this does not work, force unwrap the text in your text field and see if it produces a nil error. in CellForRowAtIndexPath

Related

Data Parsing firebase

I plan to retrieval data from Database Firebase to TableView by this code what is wrong with my code and how can i fix it to let all details send to my table view
Firebase database
Run at Phone
And this is my data in the database:
import UIKit
import Firebase
class Ordersv: UIViewController, UITableViewDataSource, UITableViewDelegate {
var array = [String]()
var ref: DatabaseReference!
var handle: DatabaseHandle!
#IBOutlet weak var TableView: UITableView!
#IBAction func add (_ sender: Any){
if textField.text != ""{
ref.child("list").childByAutoId().setValue(textField.text)
textField.text = ""
}
}
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
handle = ref?.ref.child ("Orders/Customer/Detils/").observe(.value, with: { (snapshot) in
if let item = snapshot.value as? String {
self.array.append(item)
self.TableView.reloadData()
}
})
self.TableView.delegate = self
self.TableView.dataSource = self
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = TableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell
cell.textLabel?.text = array[indexPath.row]
return cell
}
}
There are a few things wrong wit the code:
You never initialize ref.
When you observe .value, you get multiple nodes back. Your code doesn't handle this fact.
To fix both, I recommend:
let ref = Database.database().reference()
handle = ref.child("Orders/Customer/Detils/").observe(.childAdded, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let name = value?["Name"] as? String ?? ""
self.array.append(name)
self.TableView.reloadData()
})
The above code observes the .childAdded event, which fires immediately for each existing child node, and then once for every subsequent child that is added.

Display Firebase Data in UITableView

I am trying to make a UITableView display data from my firebase database which is in the following structure
I need the first label to display the shop's name and the shop's type. When I print the values from the database, it displays the list of the shops and the type next to it. However, I am finding it difficult to replicate this into the UITableView. Thank you for the help. Here is my code:
import UIKit
import Firebase
struct shopStruct {
let shopName: String!
let shopType : String!
}
class HomeViewController: UIViewController, UITableViewDataSource , UITableViewDelegate {
#IBOutlet weak var homeTableView: UITableView!
var databaseRef: DatabaseReference!
var shops = [shopStruct]()
override func viewDidLoad() {
super.viewDidLoad()
databaseRef = Database.database().reference()
databaseRef.child("shops").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
if let valueDictionary = snapshot.value as? [AnyHashable:String]
{
let shopName = valueDictionary["name"]
let shopType = valueDictionary["type"]
self.shops.insert(shopStruct(shopName: shopName, shopType: shopType), at: 0)
self.homeTableView.reloadData()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let label1 = cell.viewWithTag(1) as! UILabel
label1.text = shops[indexPath.row].shopName
let label2 = cell.viewWithTag(2) as! UILabel
label2.text = shops[indexPath.row].shopType
return cell
}
}
You have to set in viewDidLoad
self.homeTableView.dataSource = self
May be it's not working because you'r reloading the tablebview on secondary thread so could you please replace the code self.homeTableView.reloadData() with following code and try?
DispatchQueue.main.async {
self.homeTableView.reloadData()
}

FireBase is returning strings as nil

Man, UITableView's just do not want to work with me. I have been outputting strings to Firebase storage and I see the values stored. My problem is that I cannot output any of those strings into the UITableView. I just see a blank table view and when I go and try to see what is being outputted by thoughtObjects.thoughts it just says "nil." If anyone can help figure out what is wrong that would be appreciated. Thank you so much StackOverflow.
import UIKit
import Firebase
import FirebaseDatabase
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var inputThoughtTextField: UITextField!
#IBOutlet weak var successfulUploadLbl: UILabel!
#IBOutlet weak var tableView: UITableView!
var refThoughts: DatabaseReference!
var thoughtList = [ThoughtModel]()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return thoughtList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
//creating a cell using the custom class
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! VCTableViewCell
//the artist object
let thoughtObjects: ThoughtModel
//getting the artist of selected position
thoughtObjects = thoughtList[indexPath.row]
//adding values to labels
cell.wordCloud.text = thoughtObjects.thoughts
//print(cell.wordCloud.text)
//returning cell
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
refThoughts = Database.database().reference().child("thoughts");
refThoughts.observe(DataEventType.value, with: { (snapshot) in
//if the reference have some values
if snapshot.childrenCount > 0 {
//clearing the list
self.thoughtList.removeAll()
//iterating through all the values
for thoughts in snapshot.children.allObjects as! [DataSnapshot] {
//getting values
let thoughtsObject = thoughts.value as? [String: AnyObject]
let thoughtText = thoughtsObject?["thoughts"]
let thoughtId = thoughtsObject?["id"]
//creating artist object with model and fetched values
let thoughtCreation = ThoughtModel(id: thoughtId as! String?, thoughts: thoughtText as! String?)
//appending it to list
self.thoughtList.append(thoughtCreation)
}
//reloading the tableview
self.tableView.reloadData()
}
})
}
#IBAction func buttonAddThought(_ sender: UIButton){
addThought()
}
func addThought(){
let key = refThoughts.childByAutoId().key
let thought = ["id": key,
"Thoughts": inputThoughtTextField.text! as String
]
refThoughts.child(key).setValue(thought)
successfulUploadLbl.text = "Thought Uploaded"
}
}

Present list of items in tableview from Realm database

I am successfully downloading and printing data from Realm database. Here is my log:
Item(id: Optional(0), name: Optional("Item (0)"), descr: Optional("Description of item (0)"),
icon: Optional("http://192.168.1.101:8080/api/items/0/icon.png"),
url: Optional("http://192.168.1.101:8080/api/items/0")))
Now I have to assign those values on actual list and I am getting a clean sheet tableview. How to do it properly? I am using .xib as tablewViewCell. I am thankful for any tips.
class ItemRealm : Object {
dynamic var id = 0
dynamic var name = ""
dynamic var desc = ""
dynamic var icon = ""
override class func primaryKey() -> String? {
return "id"
}
}
class ViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
let realm = try! Realm()
let results = try! Realm().objects(ItemRealm.self).sorted(byKeyPath: "id")
let SERVER_URL = "http://192.168.1.101:8080/api/items"
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(SERVER_URL).responseJSON { response in
let items = [Item].from(jsonArray: response.result.value as! [Gloss.JSON])
print(items?[0] as Any)
try! self.realm.write {
for item in items! {
let itemRealm = ItemRealm()
itemRealm.id = item.id!
itemRealm.name = item.name!
itemRealm.desc = item.descr!
itemRealm.icon = item.icon!
self.realm.add(itemRealm)
}
}
_ = self.realm.objects(ItemRealm.self)
// print(items?[0] as Any)
}
// Do any additional setup after loading the view.
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
}
// MARK: - UITableView data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
var object: ItemRealm
object = self.results[indexPath.row] as ItemRealm
cell.item = object
return cell
}
}
I think you are missing self.tableView.reloadData() after getting data from the response. Consider also assigning fetched data to your results variable.

Error while trying to download Image URL from Firebase database using Swift3

Would you please help me to find the error in my code? I have an image URL in my database and I'm trying to download it and display it in a TableView, but it shows nil value.
This is my Class:
class Post : NSObject {
var Posts : String!
var Image : String!
}
and this is My TableView.
import UIKit
import FirebaseDatabase
import SDWebImage
class ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate {
#IBOutlet weak var MyImageView: UIImageView!
#IBOutlet weak var tableView: UITableView!
var Ref:FIRDatabaseReference?
var Handle:FIRDatabaseHandle?
var myarray = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.delegate = self
tableView.dataSource = self
}
override func viewDidAppear(_ animated: Bool) {
Ref=FIRDatabase.database().reference()
Handle = Ref?.child("Posts").observe(.childAdded ,with: { (snapshot) in
let post = snapshot.value as? Post
self.myarray.append(post!)
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return myarray.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as? TableViewCell {
// cell?.textLabel?.text = PostData[indexPath.row]
let url = URL(string : self.myarray [(indexPath as NSIndexPath).row].Image!)
cell.MyImage.sd_setImage(with: url)
return cell
}else{
let cell = TableViewCell()
let url = URL(string : self.myarray [(indexPath as NSIndexPath).row].Image!)
cell.MyImage.sd_setImage(with: url)
return cell
}
}
}

Resources