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.
Related
I have been trying to retrieve profile data from firebase realtime database and displaying it in a table view, so far when I run the simulator the tabelview shows up blank and Failed : error 0:50 [50] shows up. I am pretty new to swift and am not sure what the problem is.
Here is my code:
import UIKit
import FirebaseDatabase
import FirebaseStorage
import FirebaseAuth
class userViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return profileData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "firstName_cell",
for: indexPath)
self.tableView.reloadData()
cell.textLabel?.text = self.profileData[indexPath.item]
return cell
}
var profileData = [String]()
let storageRef = Storage.storage().reference()
var databaseRef = Database.database().reference()
var ref: DatabaseReference?
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
//let userID = Auth.auth().currentUser?.uid
ref?.child("users").observeSingleEvent( of: .childAdded, with: { (snapshot) in
let profile = snapshot.value as? String
if let actualProfile = profile{
self.profileData.append(actualProfile)
print(self.profileData)
self.tableView.reloadData()
}
}) { (error) in
print(error.localizedDescription)
}
}
}
Don’t add reloadData() in cellForRow method.... it will become infinite loop .. so remove self.tableView.reloadData() from cellForRow method
You try to reload your tableView while its reloading.
You should not call tableView.reloadData() in tableView(_:cellForRowAt:) method or any other UITableViewDataSource method that is called from same UITableView.
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
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()
}
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"
}
}
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.