I was making an app for one of my family members so that they could better manage their clients but ran into some issues. This is my first time using Firebase and I just can't seem to get my code to work! The part in which I am getting stuck involves Firebase's Realtime Database, and I am working in XCode 8.3 with Swift 3.1.
Code:
import UIKit
import FirebaseCore
import FirebaseDatabase
import FirebaseAuth
var specClientId = ""
class MyCell: UITableViewCell {
#IBOutlet var nameCell: UILabel!
#IBOutlet var statusCell: UILabel!
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tableView: UITableView!
var ref: FIRDatabaseReference!
var tableArray: [String] = []
var clientId: [String] = []
var statusArray:[String] = []
#IBAction func signOut(_ sender: Any) {
UserDefaults.resetStandardUserDefaults()
performSegue(withIdentifier: "segueBackLogin", sender: self)
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableArray.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellFront") as! MyCell
cell.nameCell.text = tableArray[indexPath.row]
cell.statusCell.text = statusArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
specClientId = clientId[indexPath.row]
ref.child("Users").child(specClientId).child("lastUpdate").removeValue()
performSegue(withIdentifier: "segue", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
if FIRApp.defaultApp() == nil {
FIRApp.configure()
}
ref = FIRDatabase.database().reference()
ref.child("Users").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let specificValues = value?.allKeys
self.tableArray.removeAll()
self.statusArray.removeAll()
self.clientId.removeAll()
var it = 0
for Uservalue in specificValues! {
self.tableArray.append("")
self.statusArray.append("")
self.clientId.append(Uservalue as! String)
self.ref.child("Users")
.child(Uservalue as! String)
.child("name")
.observeSingleEvent(of: .value, with: { (snapshot) in
let nameValue = snapshot.value as? String
self.tableArray.insert(nameValue!, at: it)
self.tableArray = self.tableArray.filter {$0 != ""}
self.tableView.reloadData()
}) { (error) in
print(error.localizedDescription)
}
self.ref.child("Users")
.child(Uservalue as! String)
.child("lastUpdate")
.observeSingleEvent(of: .value, with: { (snapshot) in
if let nameValue = snapshot.value as? String {
self.statusArray.insert("*", at: it)
self.tableView.reloadData()
} else {
self.statusArray.insert("", at: it)
self.tableView.reloadData()
}
}) { (error) in
print(error.localizedDescription)
}
it += 1
}
}) { (error) in
print(error.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
My main issue is that when I get the user's name and their lastUpdate status, the array lists do not match up correctly and the TableView displays the wrong information in terms of which User has submitted their updates. To fix this issue, I tried to use the insert method in my arrays but now the app crashes. Previously, I was using the append method but that leads to the wrong information being displayed in the TableView. I would appreciate it if any of you could help me with this issue.
Note: The App Crashes due to the StatusArray not having the same amount of elements as the TableArray. This is caused by the TableArray having some empty elements with no names in them.
Thanks,
KPS
Edit 1:
for Uservalue in specificValues! {
self.clientId.append(Uservalue as! String)
let user = User()
self.ref.child("Users")
.child(Uservalue as! String)
.observeSingleEvent(of: .value, with: { (snapshot) in
let nameValue = snapshot.value as? NSDictionary
let specNameValue = nameValue?.allKeys
var i = 0
while i < specNameValue!.count {
if specNameValue?[i] as? String == "name" {
user.name = nameValue?.allValues[i] as! String
} else if specNameValue?[i] as? String == "lastUpdate" {
user.status = "*"
} else if specNameValue?[i] as? String != "name" && specNameValue?[i] as? String != "lastUpdate" && specNameValue?[i] as? String != "message" && specNameValue?[i] as? String != "adminMessage" && specNameValue?[i] as? String != "photoURL" {
user.status = ""
}
i += 1
}
}) { (error) in
print(error.localizedDescription)
}
self.tableArray.append(user)
self.tableView.reloadData()
}
The main reason your app is crashing is because in your cell for row you are reloading after loading the first user and the cell expects the statusArray to have elements already.
cell.nameCell.text = tableArray[indexPath.row]
cell.statusCell.text = statusArray[indexPath.row] // fails here I assume
There a few issues going on here that I'll try to address.
You are reloading the table immediately for each child that is iterated through. It would be smart to append elements to each array then once completed display all elements by calling tableView.reloadData()
Are status' independent of the name that you are expecting? If the data is correlated, it would be smart to create a simple Object to house this data and have a single array of data that the tableView will use for it's dataSource
Once your data is fully loaded, you could sort the data accordingly then reload the datasource to solve the issue of pulling data from the server that is out of order. This is why the append(element: ) is simple and useful
Hopefully this helps! It may seem like a bit more work but it would definitely be beneficial to performance, organization and readability for yourself.
Related
I can load my current tableview data onto the database and then print out the new data onto my console but can't get the new data back into the tableview and I'm tearing my hair out because I know it should be simple!
I've tried all sorts of things but I just can't figure out where I'm going wrong.
//Saves to database without any problems
//Class
var ref: DatabaseReference!
//ViewDidLoad
ref = Database.database().reference()
func save()
{
let ref = Database.database().reference(withPath: "Admin")
let adding = ref.child(me)
let addData: [String: [String]] = ["addJokes": data]
adding.setValue(addData)
{
(error:Error?, ref:DatabaseReference) in
if let error = error
{
print("Data could not be saved: \(error).")
}
else
{
print("Data saved successfully!")
}
}
}
Can print out the database data to my console but can't get it into my tableview
let ref = Database.database().reference(withPath: "Admin")
ref.observe(.value, with:
{
(snapshot) in
let new = snapshot.value as? String
print(snapshot.value as Any)
if let newData = new
{
self.data.append(newData)
self.mainTable.reloadData()
}
})
Update
TableView details-
TableView Class Ext
extension TableView: UITableViewDataSource, UITableViewDelegate
{
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if isSearching {
return filteredArray.count
}
else
{
return data.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
var array: String?
if isSearching
{
array = filteredArray[indexPath.row]
}
else
{
array = data[indexPath.row]
}
let cell = mainTable.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as UITableViewCell
cell.textLabel?.text = array
return cell
}
TableView Class-
class TableView: UIViewController
{
let cellId = "cellId"
var filteredArray = [String]()
var ref: DatabaseReference!
var data = [
"""
multiple line
data array
"""
]
lazy var mainTable: UITableView =
{
let table = UITableView()
table.translatesAutoresizingMaskIntoConstraints = false
table.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
return table
}()
override func viewDidLoad() {
super.viewDidLoad()
mainTable.delegate = self
mainTable.dataSource = self
}
Console prints exactly what I want back into my tableview. Turning print function into results is usually the easy part.
The problem lies in let new = snapshot.value as? String. Here, new is null thus if let newData = new is always false and if block won't be executed. First, check snapshot.value's data type and value then use it accordingly.
I am building an app which uses Firebase's database service. I am trying to load the data into a table view but I am unable to do so. I can't seem to figure out what's going wrong. The code is also not giving me any errors. I've checked the database permissions on Firebase and they seem to be good. Here's my code:
import UIKit
import Firebase
struct postStruct {
let word : String!
let wordType : String!
}
class sentenceBuilderViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var wordSearchBar: UISearchBar!
#IBOutlet weak var wordsTableView: UITableView!
var posts = [postStruct]()
override func viewDidLoad() {
wordsTableView.reloadData()
getWordsFromDatabase()
super.viewDidLoad()
wordsTableView.delegate = self
wordsTableView.dataSource = self
}
func getWordsFromDatabase() {
let databaseRef = Database.database().reference()
databaseRef.child("wordList").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: {
snapshot in
let word = (snapshot.value as? NSDictionary)!["word"] as? String
let wordType = (snapshot.value as? NSDictionary
)!["wordType"] as? String
self.posts.insert(postStruct(word: word, wordType: wordType), at: 0)
})
wordsTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = wordsTableView.dequeueReusableCell(withIdentifier: "Cell")
let wordLabel = cell?.viewWithTag(1) as! UILabel
wordLabel.text = posts[indexPath.row].word
let wordTypeLabel = cell?.viewWithTag(2) as! UILabel
wordTypeLabel.text = posts[indexPath.row].wordType
return cell!
}
}
Any help and inputs would be appreciated! Thanks!
The problem is that you are just observing a single event here:
databaseRef.child("wordList").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: {
snapshot in
What this does is that it justs goes through your database and once it finds any child, it displays that one without going further. What you need to do is change it to observe like this:
func getAllWordsFromDatabase() {
let databaseRef = Database.database().reference()
databaseRef.child("wordList").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
let word = (snapshot.value as? NSDictionary)!["word"] as? String
let wordType = (snapshot.value as? NSDictionary)!["wordType"] as? String
self.posts.append(postStruct(word: word, wordType: wordType))
DispatchQueue.main.async {
self.wordsTableView.reloadData()
}
})
}
Try implementing this and it should work.
Move the "getWordsFromDatabase()" line in "viewDidLoad" function to AFTER you assign the delegate and data source, like this:
override func viewDidLoad() {
super.viewDidLoad()
wordsTableView.delegate = self
wordsTableView.dataSource = self
getWordsFromDatabase()
}
Also you can try to add a "reloadData()" method in the databaseRef block on the main queue, like this:
let databaseRef = Database.database().reference()
databaseRef.child("wordList").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: {
snapshot in
let word = (snapshot.value as? NSDictionary)!["word"] as? String
let wordType = (snapshot.value as? NSDictionary
)!["wordType"] as? String
self.posts.insert(postStruct(word: word, wordType: wordType), at: 0)
DispatchQueue.main.async {
wordsTableView.reloadData()
}
})
I have a database on Firebase and a tableview.
I have a list of brands, models, and year for motorcycles and I want to retrieve the list of brands on the tableview.
The problem is the DB has duplicates values. There is more than one motorcycle from Suzuki, there is more one models of SV 650, etc.
How can I check duplicates values, put it in a new array, and retrieve it in the tableview?
This is my TableViewController file:
import UIKit
import FirebaseAuth
import FirebaseDatabase
class SelectionMarqueViewController: UITableViewController {
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
loadMarques()
}
func loadMarques() {
var ref : DatabaseReference?
ref = Database.database(url: "https://myride-test.firebaseio.com/").reference()
ref?.observe(.childAdded, with: { (snapshot) in
if let dict = snapshot.value as? [String: Any] {
let MarqueText = dict["Marque"] as! String
let post = Post(MarqueText: MarqueText)
self.posts.append(post)
print(self.posts)
self.tableView.reloadData()
}
})
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath)
cell.textLabel?.text = posts[indexPath.row].Marque
return cell
}
}
And this one is the file with the Post func:
import Foundation
class Post {
var Marque: String
init(MarqueText: String) {
Marque = MarqueText
}
}
Here my Firebase Database:
Actually the tableview shows the complete list of brands in the DB, and so, many times the same brands.
On the DB and code:
"Marque" correspond to the brand.
You can implement Hashable
class Post : Hashable {
var marque: String
init(marqueText: String) {
marque = marqueText
}
// Equatable for contains
static func == (lhs:Post,rhs:Post) -> Bool {
return lhs.marque == rhs.marque
}
// Hashable for Set
var hashValue:Int {
return marque.hashValue
}
}
and use
if let dict = snapshot.value as? [String: Any] {
let MarqueText = dict["Marque"] as! String
let post = Post(MarqueText: MarqueText)
self.posts.append(post)
self.posts = Array(Set(self.posts))
print(self.posts)
self.tableView.reloadData()
}
Or simply
let marqueText = dict["Marque"] as! String
if !self.posts.map { $0.marqueText}.contains(marqueText) {
let post = Post(marqueText:marqueText)
self.posts.append(post)
self.tableView.reloadData()
}
Check and append if the marque is not available in the datasource of the tableview.
func appendMarqueAndReloadIfNeeded(_ marque: String) {
if self.posts.map({ $0.Marque }).contains(marque) {
// Do nothing
} else {
self.posts.append(Post(MarqueText: marque))
self.tableView.reloadData()
}
}
Then you call it inside observe:
///....
if let dict = snapshot.value as? [String: Any] {
let MarqueText = dict["Marque"] as! String
self.appendMarqueAndReloadIfNeeded(MarqueText)
}
///....
I am a swift beginner,and I want to get value from firebase database,but it always recived twice same dictionary structure,and can't put value in tableview cells when I unwrapping it crashed...
here is my JSON format
Code work
import UIKit
import Firebase
//import FirebaseAuthUI
//import FirebaseGoogleAuthUI
//import FirebaseFacebookAuthUI
let device = FIRDatabase.database().reference()
class MainTableViewController: UITableViewController
{
var dic:NSDictionary?
override func viewDidLoad()
{
super.viewDidLoad()
//獲取當前登陸用戶
FIRAuth.auth()?.addStateDidChangeListener(self.UserAlive(auth:user:))
print("主畫面viewDidLoad")
}
func UserAlive(auth: FIRAuth, user: FIRUser?)
{
if user == nil
{
self.present((self.storyboard?.instantiateViewController(withIdentifier: "SignIn"))!, animated: true, completion: nil)
}
else
{
csGolbal.g_User = user
CheckData()
}
}
func CheckData()
{
print("CHECKDATA")
let ref = device.child("USER").child(csGolbal.g_User!.email!.replacingOccurrences(of: ".", with: "_"))
ref.observeSingleEvent(of: .value, with:
{ (snapshot) in
if snapshot.exists()
{
csGolbal.g_key = ((snapshot.value as AnyObject).allKeys)!
}
ref.child(csGolbal.g_key![0] as! String).observeSingleEvent(of: .value, with:
{ (snapshot) in
// Get user value
self.dic = snapshot.value as? NSDictionary
print(self.dic)
//self.tableView.reloadData()
})
})
}
and here is I don't get it how to put in
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if let number = csGolbal.g_key?.count
{
return number
}
else
{
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell", for: indexPath) as! MainTableViewCell
//put in here
// label.text and ImageView
return cell
}
please hlep me,and tell me where I am do wrong.
#dahiya_boy I try your function
func getDataFromDB()
{
DispatchQueue.main.async( execute: {
//let dbstrPath : String! = "Firebase Db path"
let ref = device.child("USER").child(csGolbal.g_User!.email!.replacingOccurrences(of: ".", with: "_"))
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if !snapshot.exists()
{
print("snapshot not exists")
}
else
{
for item in snapshot.children
{
let number = item as! FIRDataSnapshot
var aDictLocal : [String : String] = number.value! as! [String : String]
aDictLocal.updateValue(number.key, forKey: "key")
print("value \(number.value!) And Key \(number.key)") // Here you got data
}
}
self.tableView.reloadData()
})
})
}
and the result feedback twice
Actually you have stored Data in DB in random key so use below func
func getDataFromDB(){
DispatchQueue.main.async( execute: {
let dbstrPath : String! = "Firebase Db path)"
dbRef.child(dbstrPath!).observeSingleEvent(of: .value, with: { (snapshot) in
if !snapshot.exists(){
print("snapshot not exists")
}
else{
self.arrEmail.removeAll() // Add this
for item in snapshot.children {
let number = item as! FIRDataSnapshot
var aDictLocal : [String : String] = number.value! as! [String : String]
aDictLocal.updateValue(number.key, forKey: "key")
self.arrEmail.append(aDictLocal) // add this
print("value \(number.value!) And Key \(number.key)") // Here you got data
}
}
// self.tblContacts.reloadData()
})
})
}
Edit
Create one global array like below in your VC
var arrEmail = [[String : String]]() // Assuming your key and value all string
In the above code work add two lines (I edited and with comment add this)
self.arrEmail.removeAll()
and
self.arrEmail.append(aDictLocal) // Now in arrEmail you have all the values for every random key.
I have the following JSON Firebase database:
{ "fruits": {
"apple": {
"name": "Gala",
"url": "//s-media-cache-ak0.pinimg.com/564x/3e/b1/e7/3eb1e756d66856975d6e43ebb879200a.jpg",
"fruitArray": [1, 2]
},
"orange": {
"name": "Tangerine",
"url": "//userscontent2.emaze.com/images/0ba588c8-42d9-45e9-a843-d19e5720515a/e430f9a827f139e9f99f2826175dd0a9.jpg",
"fruitArray": []
}
}
}
the following Fruit class:
class Fruit {
var name: String
var url: String
var fruitArray: [Int]
var ref: FIRDatabaseReference?
init(name: String, url: String, fruitArray: [Int]) {
self.name = name
self.url = url
self.fruitArray = fruitArray
self.ref = nil
}
init(snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String: Any]
name = snapshotValue["name"] as! String
url = snapshotValue["url"] as! String
if snapshotValue["fruitArray"] == nil {
fruitArray = [0]
} else {
fruitArray = snapshotValue["fruitArray"] as! [Int]
}
ref = snapshot.ref
}
func toAnyObject() -> Any {
return [
"name": name,
"url": url,
"fruitArray": fruitArray
]
}
And the following FruitTableViewController Code:
class FruitTableViewController: UITableViewController {
// MARK: Properties
var fruits: [Fruit] = []
override func viewDidLoad() {
super.viewDidLoad()
let ref = FIRDatabase.database().reference(withPath: "fruits")
ref.queryOrdered(byChild: "name").observe(.value, with: { snapshot in
var addedFruits: [Fruit] = []
for fruit in snapshot.children {
let newFruit = Fruit(snapshot: fruit as! FIRDataSnapshot)
addedFruit.append(newFruit)
}
self.fruits = addedFruits
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? FruitTableViewCell
let fruit = fruits[indexPath.row]
let imgURL = NSURL(string: fruit.url)
if imgURL != nil {
let data = NSData(contentsOf: (imgURL as? URL)!)
cell.icon.image = UIImage(data: data as! Data)
}
cell.nameLabel.text = fruit.name
return cell
}
For some reason, the Firebase snapshot is not working. I've tried almost everything with no luck.
It's not a TableViewCell issue (I think) because I checked the FruitViewCell and Storyboard and everything is in order. My hunch is that it has something to do with the way I'm changing the URL to a string as well as the array. I've used this exact code for a different iOS project and it worked but the difference between the two projects is that this one has an array and link within the JSON while the other one didn't.
I've seen that there are other ways to take a snapshot but I'm going to use the fruit data throughout the app and thus it's easier for me to have a Fruit object, but I wouldn't mid if someone were to suggest an alternate way of taking a snapshot that works. Any help is appreciated!
First of all change your viewDidLoad with this code as addedFruites is not needed at all
override func viewDidLoad() {
super.viewDidLoad()
let ref = FIRDatabase.database().reference().child("fruits")
ref.observe(.value, with: { snapshot in
if snapshot.exists() {
for fruit in snapshot.children {
let newFruit = Fruit(snapshot: fruit as! FIRDataSnapshot)
self.fruits.append(newFruit)
}
self.tableView.reloadData()
}
})
}
check firebase rules for read and write is properly set or not.. I think here is an issue because may be you did not set that rules.