Can't view Firebase data in tableview Swift 4 - swift

Im having a issue where I can't view anything that I write to my Firebase database in my table view. I previously had some working code to view my database entries but had to revise how I write data to the database so I can save the unique ID generated by childByAutoID(), so I may delete an entry later. Here's my code:
Heres how I write to Firebase:
ref = Database.database().reference() // sets the variable "ref" to connect to our Firebase database
let key = ref?.child("task").childByAutoId().key
let post = ["uid": key, // Gets auto generated ID for database entry
"title": input.text, // Saves the title field to Firebase
"description": inputField.text] // Saves the description field to Firebase
ref?.child("task").child(key!).setValue(post) // Saves the task for Firebase, ties each post with a unique ID
var arr : [(String, String)] = [];
for (key, value) in post {
arr.append((key, value!));
Heres my TableViewController:
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return (arr.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = UITableViewCell(style:
UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
let (key, value) = arr[indexPath.row]; //read element for the desired cell
cell.textLabel?.text = key
cell.detailTextLabel?.text = value
return (cell)
}
override func viewDidAppear(_ animated: Bool) {//change "viewDidLoad()" back to "viewDidAppear()"
ref = Database.database().reference() // sets the variable "ref" to connect to our Firebase database
list.removeAll() // Deletes all older data, so only data thats on the Firebase Database will be added to the "list" array
desc.removeAll() // Deletes all older data, so only data thats on the Firebase Database will be added to the "desc" array
handle = ref?.child("task").observe(.childAdded, with: { (snapshot) in
if let item = snapshot.value as? String
{
arr.append(item)
list.append(item)
//desc.removeAll()
self.myTableView.reloadData()
}
})
}

Firebase returns the items in form of NSArray or NSDictionary or NSString. (Refer here)
Since your post object is NSDictionary, parse the snapshot value as a Array of Dictionary. try the following:
if let itemArray = snapshot.value as? [[String : Any]] {
// Looping logic on 'itemArray' to get your sent dictionaries on the firebase
// After looping logic add Ui logic out of loop
}

Related

Swift after iterating list.count always 0 [duplicate]

I have an array of struct called displayStruct
struct displayStruct{
let price : String!
let Description : String!
}
I am reading data from firebase and add it to my array of struct called myPost which is initialize below
var myPost:[displayStruct] = []
I made a function to add the data from the database to my array of struct like this
func addDataToPostArray(){
let databaseRef = Database.database().reference()
databaseRef.child("Post").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
let snapshotValue = snapshot.value as? NSDictionary
let price = snapshotValue?["price"] as! String
let description = snapshotValue?["Description"] as! String
// print(description)
// print(price)
let postArr = displayStruct(price: price, Description: description)
self.myPost.append(postArr)
//if i print self.myPost.count i get the correct length
})
}
within this closure if I print myPost.count i get the correct length but outside this function if i print the length i get zero even thou i declare the array globally(I think)
I called this method inside viewDidLoad method
override func viewDidLoad() {
// setup after loading the view.
super.viewDidLoad()
addDataToPostArray()
print(myPeople.count) --> returns 0 for some reason
}
I want to use that length is my method below a fucntion of tableView
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myPost.count --> returns 0
}
Any help would be greatly appreciated!
You making a asynchronous network request inside closure and compiler doesn't wait for the response, so just Reload Table when get post data. replace the code with below it work works fine for you. All the best.
func addDataToPostArray(){
let databaseRef = Database.database().reference()
databaseRef.child("Post").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
let snapshotValue = snapshot.value as? NSDictionary
let price = snapshotValue?["price"] as! String
let description = snapshotValue?["Description"] as! String
// print(description)
// print(price)
let postArr = displayStruct(price: price, Description: description)
self.myPost.append(postArr)
print(self.myPost.count)
print(self.myPost)
self.tableView.reloadData()
//if i print self.myPost.count i get the correct length
})
}
Firebase observe call to the database is asynchronous which means when you are requesting for the value it might not be available as it might be in process of fetching it.
That's why your both of the queries to count returns 0 in viewDidLoad and DataSource delegeate method.
databaseRef.child("Post").queryOrderedByKey().observe(.childAdded, with: { // inside closure }
Inside the closure, the code has been already executed and so you have the values.
What you need to do is you need to reload your Datasource in main thread inside the closure.
databaseRef.child("Post").queryOrderedByKey().observe(.childAdded, with: {
// After adding to array
DispatchQueue.main.asyc {
self.tableView.reloadData()
}
}

Swift showing Firebase duplicating data (.observeChildAdded) not working

Each time I add a new post to the database, the amount of times the posts show is increased by one. For instance, when I add one new post, the number of times the posts are duplicated is once. When I add another post (the view is reloaded) I see all the posts three times. I assume that the problem is with the function fetchPosts(), as each time the view loads it collects all the data from the firebase and appends it to the array. I have already tried emptying the array in the view did load, but that only makes all the posts show even more times. Also, I have tried using observe(.childAdded) and that results in no posts showing at all.
var ref: DatabaseReference!
var postList = [Post]()
var refHandle : UInt!
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
checkForSignedIn ()
ref = Database.database().reference().child("posts")
fetchPosts()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PostTableViewCell
//set cell content
let contentOfCellPost = postList[indexPath.row]
cell.label?.text = contentOfCellPost.post_words
cell.revealCount.text = contentOfCellPost.Reveals
return cell
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let tableSize = tableView.bounds.height
return tableSize
}
func fetchPosts () {
let query = ref.queryOrdered(byChild: "timestamp").queryLimited(toFirst: 10)
query.observe(.value) { (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
if let value = child.value as? NSDictionary {
let post = Post()
let poster = value["poster"] as? String ?? "Name not found"
let post_content = value["post"] as? String ?? "Content not found"
let post_reveals = value["Reveals"] as? String ?? "Reveals not found"
post.post_words = post_content
post.poster = poster
post.Reveals = post_reveals
post.postID = child.key
self.postList.append(post)
print (post.post_words ?? "none")
DispatchQueue.main.async { self.tableView.reloadData() }
//make this for when child is added but so that it also shows psots already there something like query.observre event type of
}
}
}
}
The console log at first, for instance, will show the correct number of posts :
Thrice
Twice
Once
Tttt
Bloop
Decimal
9
7
3
When I add a new post, it shows this:
Tattoo
Thrice
Twice
Once
Tttt
Bloop
Decimal
9
7
3
Tattoo
Thrice
Twice
Once
Tttt
Bloop
Decimal
9
7
3
Tattoo
Thrice
Twice
Once
Tttt
Bloop
Decimal
9
7
3
Tattoo
Thrice
Twice
Once
Tttt
Bloop
Decimal
9
7
3
You need to clear your model (self.postList) at the beginning of the .observe block like so:
query.observe(.value) { (snapshot) in
self.postList.removeAll() //or however you can clear it
for child in snapshot.children.allObjects as! [DataSnapshot] {
if let value = child.value as? NSDictionary {
let post = Post()
let poster = value["poster"] as? String ?? "Name not found"
let post_content = value["post"] as? String ?? "Content not found"
let post_reveals = value["Reveals"] as? String ?? "Reveals not found"
post.post_words = post_content
post.poster = poster
post.Reveals = post_reveals
post.postID = child.key
self.postList.append(post)
print (post.post_words ?? "none")
DispatchQueue.main.async { self.tableView.reloadData() }
//make this for when child is added but so that it also shows psots already there something like query.observre event type of
}
}
Currently, each time the database is updated with a post, you add all posts to your model once again. Therefore you must clear your model each time you fetch all posts.
The reason why this doesn't work in viewDidLoad is because viewDidLoad is called only once, in the beginning, and not everytime the view appears -- thus the data will not be cleared upon adding a post.
Alternatively, you can use .childAdded -- but then you need to change the way you parse it because each snapshot with .childAdded returns a single post, not all the posts together.

Read the value of an attribute of a Core Data entity

I'm trying to read the value of an attribute (called 'name') of an entity (called 'List'), stored in a Core Data database. The issue that I have is that it says that the value of that attribute is nil, which should be a String.
My code for retrieving all List-entities is as follows:
container?.performBackgroundTask { [weak self] context in
self?.wordLists = try! List.all(in: context)
DispatchQueue.main.async(execute: {
print("Main queue available, reloading tableview.")
self?.wordListSelector.reloadData()
})
}
class func all(in context: NSManagedObjectContext) throws -> [List] {
let listRequest: NSFetchRequest<List> = List.fetchRequest()
do {
let list = try context.fetch(listRequest)
print(list)
return list
} catch {
print("error")
throw error
}
}
This prints:
[<__Words.List: 0x6000000937e0> (entity: List; id: 0xd00000000004000c <x-coredata://999D0158-64BD-44FD-A0B1-AB4EC03B9386/List/p1> ; data: <fault>), <__Words.List: 0x600000093a60> (entity: List; id: 0xd00000000008000c <x-coredata://999D0158-64BD-44FD-A0B1-AB4EC03B9386/List/p2> ; data: <fault>), <__Words.List: 0x600000093ab0> (entity: List; id: 0xd0000000000c000c <x-coredata://999D0158-64BD-44FD-A0B1-AB4EC03B9386/List/p3> ; data: <fault>)]
Which shows me that there should be 3 lists in the database, which is as expected.
I have created a variable like this:
var wordLists: [List] = [] {
didSet {
print("Detected wordList update, waiting for main queue.")
DispatchQueue.main.async(execute: {
print("Main queue available, reloading tableview.")
self.wordListSelector.reloadData()
})
}
}
This variable holds the List-entities that I retrieved by calling that all() function which I mentioned previously.
The following two methods will fill my TableView:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numberOfRowsInSection: \(wordLists.count).")
return wordLists.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "CategoryCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
print("cellForRowAt: \(indexPath.row) has name \(wordLists[indexPath.row].name).")
cell.textLabel?.text = wordLists[indexPath.row].name
return cell
}
This prints the following:
Detected wordList update, waiting for main queue.
Main queue available, reloading tableview.
numberOfRowsInSection: 3.
cellForRowAt: 0 has name nil.
cellForRowAt: 1 has name nil.
cellForRowAt: 2 has name nil.
Why is the name nil? Is this because the data is still 'faulted'? By viewing topics online I thought that Core Data automaticly unfaulted its data when you try to access it. What am I doing wrong?
Edit:
If I change the didset to the following:
var wordLists: [List] = [] {
didSet {
print("Wordlist was updated.")
for wordList in wordLists {
print(wordList)
print(wordList.name)
}
}
}
It does print the names (Optional("nameofitem1")). In the cellForRowAt it still prints 'nil'.
What you do looks like a good job for the NSFetchedResultsController. That will also help with the threading you might mix up as suggested in the comments. There is really good documentation on the NSFetchedResultsController

Slow CloudKit table scrolling - altering existing code?

Below I have my existing query download and cell for table row code...
publicDB.perform(query, inZoneWith: nil)
{
(results, error) -> Void in
if (error != nil)
{
self.present(alert, animated: true, completion: nil)
}
else
{
for result in results!
{
self.restaurantArray.append(result)
}
OperationQueue.main.addOperation( { () -> Void in
self.tableView.reloadData()
}) } }}
downloadRestaurants()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantcell") as? RestaurantTableCell
let restaurant: CKRecord = restaurantArray[indexPath.row]
cell?.name?.text = restaurant.value(forKey: "Name") as? String
let asset = restaurant.value(forKey: "Picture") as! CKAsset
let data = try! Data(contentsOf: asset.fileURL)
_ = UIImage(data: data)
cell?.picture?.image = UIImage(data: data)
return cell!
}
When I run this code, the app remains functional but scrolling through the 10 or so table cells is incredibly choppy. I am unsure what is causing this - all records, each containing an image, are downloaded during the query download portion of the top function. However, a problem or concept I'm missing is ever present during runtime. What am I missing here? Lazy loading? cache? something else? Unsure at this point, so any help would be incredibly helpful.
Update 1:
I've updated my code with a large thank you going to Pierce. I've had to update my code ever so slightly from his answer to maintain a ckrecord array to segue over to another controller via - restaurantArray but also create a new array for the NSObject class - tablerestaurantarray to be displayed in the current table controller.
var restaurantArray: Array<CKRecord> = []
var tablerestaurantarray: [Restaurant] = []
for result in results!
{
let tablerestaurant = Restaurant()
if let name = result.value(forKey: "Name") as! String? {
tablerestaurant.name = name
}
// Do same for image
if let imageAsset = result.object(forKey: "Picture") as! CKAsset? {
if let data = try? Data(contentsOf: imageAsset.fileURL) {
tablerestaurant.image = UIImage(data: data)
}
}
self.tablerestaurantarray.append(tablerestaurant)
self.restaurantArray.append(result)
}
OperationQueue.main.addOperation( { () -> Void in
self.tableView.reloadData()
})
}
}
}
downloadRestaurants()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurantArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantcell") as? RestaurantTableCell
let restaurant: Restaurant = tablerestaurantarray[indexPath.row]
cell?.name?.text = restaurant.name
cell?.picture?.image = restaurant.image
return cell!
}
The way your code is setup, whenever you scroll in your UITableView, your program is converting a CKAsset into Data, and then converting that into a UIImage, and that's within every cell! That's a rather inefficient process, so try creating an NSObject called something like Restaurant that has an image property, and when you go through all the records returned from your CKQuery, parse each record into a new Restaurant object. To create a new NSObject, go to File -> New -> File -> select 'Swift File' and add something like this:
import UIKit
class Restaurant: NSObject {
// Create a UIImage property
var image: UIImage?
// Add any other properties, i.e. name, address, etc.
var name: String = ""
}
Now for your query:
// Create an empty array of Restaurant objects
var restaurantArray: [Restaurant] = []
publicDB.perform(query, inZoneWith: nil) { (results, error) -> Void in
if (error != nil) {
self.present(alert, animated: true, completion: nil)
} else {
for result in results! {
// Create a new instance of Restaurant
let restaurant = Restaurant()
// Use optional binding to check if value exists
if let name = result.value(forKey: "Name") as! String? {
restaurant.name = name
}
// Do same for image
if let imageAsset = result.object(forKey: "Picture") as! CKAsset? {
if let data = try? Data(contentsOf: imageAsset.fileURL) {
restaurant.image = UIImage(data: data)
}
}
// Append the new Restaurant to the Restaurants array (which is now an array of Restaurant objects, NOT CKRecords)
self.restaurantArray.append(restaurant)
}
OperationQueue.main.addOperation( { () -> Void in
self.tableView.reloadData()
})
}
}
Now your cell setup is much simpler:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantcell") as? RestaurantTableCell
let restaurant: Restaurant = restaurantArray[indexPath.row]
cell?.name?.text = restaurant.name
cell?.picture?.image = restaurant.image
return cell!
}
You should use CKQueryOperation in order to implements pagination for your UITableView.
You have to set the resultLimit property to a number equals to the cell quantity visiable at one time on you table plus 3 or 4
Set recordFetchedBlock property where you have to implement the code that will apply to one CKRecord
Set queryCompletionBlock property. This is the most important part on your pagination code because this closure receive an Optional CKQueryCursor parameter.
If this CKQueryCursor is nil then you have reach the last record available for you query but if it's a non nil value, then you have more records to fetch using this CKQueryCursor as indicator to your next fetch.
When user scroll on your TableView and reach the last element you should perform another fetch with CKQueryCursor.
Other performance advice is CKAssets should be treated on separated execution queues.

How can I return a numberOfRowsInSection from Firebase Async

Im retrieving counts from Firebase.children the data is async Im able to retrieve the count from a function callback but i cannot get the result out of the call back and return the rows. How can I complete this? Thank you in advance.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var number:Int!
getFirData { (result) in
number = Int(result.childrenCount)
}
return number
}
This is the async data im retrieving from Firebase
func getFirData(completion:(result:FIRDataSnapshot)->()){
let dbRef = FIRDatabase.database().reference()
let userAiD = FIRAuth.auth()?.currentUser?.uid
dbRef.child("posts").queryOrderedByChild("userAiD").queryEqualToValue(userAiD).observeEventType(.Value, withBlock: {snapshot in
let snapshot = snapshot
completion(result:snapshot )
})
}
You cannot. You'll have to fire off that query in viewDidLoad() or perhaps viewWillAppear(_:), store the values of the query for reference in a property, and call reloadData() (or relevant insert methods) on your table view.