extension of Firebase Database Structure
After uploaded the image, name and phone to the Firebase Database and Firebase Storage.
I am having trouble with retrieving the image from the Firebase to the Table View.
This is the Table View Class :
#IBOutlet var tableViewHongKong: UITableView!
var restaurantList = [RestaurantModel]()
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference().child("restaurants")
ref?.observe(FIRDataEventType.value, with: {(snapshot) in
if snapshot.childrenCount>0
{
self.restaurantList.removeAll()
for restaurants in snapshot.children.allObjects as![FIRDataSnapshot]
{
let restaurantObject = restaurants.value as? [String: AnyObject]
let restaurantName = restaurantObject?["name"]
let restaurantPhone = restaurantObject?["phone"]
let restaurant = RestaurantModel(name: name as! String?, phone: phone as! String?)
self.restaurantList.append(restaurant)
}
}
self.tableViewHongKong.reloadData()
})
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurantList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewControllerTableViewCell
let restaurant: RestaurantModel
restaurant = restaurantList[indexPath.row]
cell.nameLabel.text = restaurant.name
return cell
}
}
This is the Table View Cell Class :
#IBOutlet var myImage: UIImageView!
#IBOutlet var nameLabel: UILabel!
This is the Restaurant Model Class:
var name: String?
var phone: String?
init(name:String?, phone:String?) {
self.name = name;
self.phone = phone
}
As the image uploaded in another class, Restaurant.
var imageURL = ""
func addRestaurant()
{
ref = FIRDatabase.database().reference().child("restaurants")
let key = ref?.childByAutoId().key
let name = addName.text
let phone = addPhone.text
ref?.child(key!).setValue(["name": name, "phone": phone, "image": imageURL])
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
addImage.image = image
var data = Data()
data = UIImagePNGRepresentation(image!)!
let uniqueName = NSUUID().uuidString
let imageRef = FIRStorage.storage().reference().child("restaurantImage").child("\(uniqueName)")
imageRef.put(data, metadata: nil).observe(.success){(snapshot) in
self.imageURL = (snapshot.metadata?.downloadURL()?.absoluteString)!
}
self.dismiss(animated: true, completion: nil)
}
For more detail, may visit Firebase Database Structure
Thank you very much ! ^.^
Related
I have a tableview loading data from firebase database. When I open my app the data does not populate. when I create a new post I can see the tableview cells modifying like changed were made but the post doesn't populate. I can't figure it out.
import UIKit
import FirebaseAuth
import FirebaseDatabase
class EventsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var eventsRef: DatabaseReference?
var eventsDatabaseHandle:DatabaseHandle?
var eventsTitles = [String]()
var eventTimestamps = [String]()
var eventsLocations = [String]()
var eventsImages = [UIImage]()
#IBOutlet weak var addEventsButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
adminAuth()
eventsRef = Database.database().reference()
tableView.reloadData()
tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
tableView.delegate = self
tableView.dataSource = self
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { (snaphot) in
let eventPost = snaphot.value as! [String: Any]
self.eventTimestamps.append(eventPost["eventdate"] as! String)
self.eventsTitles.append(eventPost["eventtitle"] as! String)
self.eventsLocations.append(eventPost["eventlocation"] as! String)
let task = URLSession.shared.dataTask(with: URL(string: eventPost["ImageUrl"] as! String)!) {(data, response, error) in
if let image: UIImage = UIImage(data: data!) {
self.eventsImages.append(image)
}
}
self.tableView.reloadData()
task.resume()
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventsImages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
let image = eventsImages[indexPath.row]
cell.flyerImages.image! = image
cell.eventTitle.text! = eventsTitles[indexPath.row]
cell.eventDate.text! = eventTimestamps[indexPath.row]
cell.eventLocation.text! = eventsLocations[indexPath.row]
cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
tableView.reloadData()
return cell
}
func adminAuth() {
if (Auth.auth().currentUser!.displayName != "Neil Leon") {
self.addEventsButton.tintColor = UIColor.clear
self.addEventsButton.isEnabled = false
}
else{
self.addEventsButton.isEnabled = true
}
}
}
image of empty tableview
]
So the code below is not tested as I don't have firebase setup currently.
However, observing childAdded... the documentation says it will pass all of the current records in the database at first and will then just post new additions. So all you need to do is loop through them, setup your tableView data source and reload the table.
Rather than use multiple arrays for values I've created an array of ChurchEvent objects instead.
struct ChurchEvents {
let title: String
let location: String?
let date: Date?
let imageUrlString: String?
init(dict: [String: Any]) {
self.title = dict["title"] as String
self.location = dict["location"] as? String
// etc
}
}
var events = [ChurchEvents]()
eventsDatabaseHandle = eventsRef?.child("Church Events").observe(.childAdded, with: { snapshot in
let list = snapshot.value as? [[String : AnyObject]]
let newEvents = list.map { ChurchEvent(dict: $0) }
events.append(newEvents)
tableView.reloadData()
}
Other improvements you could make:
class EventsTableViewCell: UICollectionViewCell {
func configure(with event: ChurchEvent {
eventDate.text = event.date
eventTitle.text = event.title
eventLocation.text = event.location
// etc
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "events") as! EventsTableViewCell
let event = events[indexPath.row]
cell.configure(with: event)
return cell
}
I'm trying to pass data onto my tableview, from my cloud firestore but it just not able to retrieve the data and post it on the tableview and so far most of of my attempts have failed. since I'm transition from real-time database to Firestore.
I've used multiple resources on stack, restructured my code multiple times and have now come down to this
here is also an image of my collection in Firestore firestore collection
import Foundation
class ProductList {
var id: String?
var name: String?
var dispensaryName: String?
var category: String?,
var brand: String?
var imageUrl: String?
init(id: String?,
name: String?,
dispensaryName: String?,
brand: String?,
category: String?,
imageUrl: String?) {
self.id = id
self.name = name
self.dispensaryName = dispensaryName
self.brand = brand
self.category = category,
self.imageUrl = imageUrl
}
}
import UIKit
class ProductListCell: UITableViewCell {
#IBOutlet weak var productImage: UIImageView!
#IBOutlet weak var dispensaryName: UILabel!
#IBOutlet weak var productName: UILabel!
#IBOutlet weak var categoryLabel: UILabel!
#IBOutlet weak var categoryStrain: UILabel!
}
import UIKit
import Firebase
import FirebaseFireStore
class ProductListController: UIViewController {
#IBOutlet weak var productListTableView: UITableView!
#IBOutlet weak var menuButton: UIBarButtonItem!
var dbRef: DatabaseReference!
var productSetup: [ProductList] = []
override func viewDidLoad() {
super.viewDidLoad()
productListTableView.dataSource = self
productListTableView.delegate = self
self.productListTableView.rowHeight = UITableView.automaticDimension
self.productListTableView.estimatedRowHeight = 363
menuButton.target = self.revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
dbRef = Database.database().reference().child("products");
//observing the data changes
dbRef.observe(DataEventType.value, with: { (snapshot) in
//if the reference have some values
if snapshot.childrenCount > 0 {
//clearing the list
self.productSetup.removeAll()
//iterating through all the values
for producting in snapshot.children.allObjects as! [DataSnapshot] {
//getting values
let productObject = producting.value as? [String: AnyObject]
let id = productObject?["id"]
let name = productObject?["name"]
let dispensaryName = productObject?["dispensaryName"]
let category = productObject?["category"]
let strain = productObject?["strain"]
let imageUrl = productObject?["imageUrl"]
//creating artist object with model and fetched values
let massProducts = ProductList(id: id as! String?,
name: name as! String?,
dispensaryName: dispensaryName as! String?,
category: category as! String?,
strain: strain as! String?,
imageUrl: imageUrl as! String?)
//appending it to list
self.productSetup.append(massProducts)
}
//reloading the tableview
print(self.productSetup)
self.productListTableView.reloadData()
}
})
}
}
extension ProductListController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProductListCell") as!
ProductListCell
let production: ProductList
production = productSetup[indexPath.row]
cell.productName.text = "\(String(describing: production.brand)): \(String(describing: production.name))"
cell.dispensaryName.text = production.dispensaryName
cell.categoryLabel.text = production.category
cell.productImage.text = production.imageUrl
return cell
}
}
I have reformatted the code quickly to make it easier to understand but it could be one of many things;
Check user authenticated with firebase on the device.
Ensure you have setup security settings correctly to allow reads in firebase.
Reformatted Code
ProductListController.swift
import Firebase
class ProductListController: UIViewController {
#IBOutlet weak var productListTableView: UITableView!
#IBOutlet weak var menuButton: UIBarButtonItem!
var productSetup = [ProductList]()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
productListTableView.dataSource = self
productListTableView.delegate = self
productListTableView.rowHeight = UITableView.automaticDimension
productListTableView.estimatedRowHeight = 363
menuButton.target = self.revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
fetchProducts { (products) in
self.productSetup = products
self.productListTableView.reloadData()
}
}
func fetchProducts(_ completion: #escaping ([ProductList]) -> Void) {
let ref = Firestore.firestore().collection("products")
ref.addSnapshotListener { (snapshot, error) in
guard error == nil, let snapshot = snapshot, !snapshot.isEmpty else {
return
}
completion(snapshot.documents.compactMap( {ProductList(dictionary: $0.data())} ))
}
}
}
extension ProductListController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProductListCell") as?
ProductListCell else { return UITableViewCell() }
cell.configure(withProduct: productSetup[indexPath.row])
return cell
}
}
ProductListCell.swift
import Firebase
class ProductListCell: UITableViewCell {
#IBOutlet weak var productImage: UIImageView!
#IBOutlet weak var dispensaryName: UILabel!
#IBOutlet weak var productName: UILabel!
#IBOutlet weak var categoryLabel: UILabel!
#IBOutlet weak var categoryStrain: UILabel!
func configure(withProduct product: ProductList) {
productName.text = "\(String(describing: product.brand)): \(String(describing: product.name))"
dispensaryName.text = product.dispensaryName
categoryLabel.text = product.category
fetchImage(withURL: product.imageUrl ) { (image) in
productImage.image = image
}
}
func fetchImage(withURL url: String, _ completion: #escaping (UIImage) -> Void) {
let ref = Storage.storage().reference(forURL: url)
ref.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
guard error == nil, let imageData = data, let image = UIImage(data: imageData) else {
return
}
completion(image)
}
}
}
ProductList.swift
class ProductList {
var id: String
var name: String
var dispensaryName: String
var category: String
var brand: String
var imageUrl: String
init(id: String, name: String, dispensaryName: String, brand: String, category: String, imageUrl: String) {
self.id = id
self.name = name
self.dispensaryName = dispensaryName
self.brand = brand
self.category = category
self.imageUrl = imageUrl
}
convenience init(dictionary: [String : Any]) {
let id = dictionary["id"] as? String ?? ""
let name = dictionary["name"] as? String ?? ""
let dispensaryName = dictionary["dispensaryName"] as? String ?? ""
let brand = dictionary["brand"] as? String ?? ""
let category = dictionary["category"] as? String ?? ""
let imageUrl = dictionary["imageUrl"] as? String ?? ""
self.init(id: id, name: name, dispensaryName: dispensaryName, brand: brand, category: category, imageUrl: imageUrl)
}
}
I Hope you found this helpful.
The problem in the given code is, that the Firebase Data is not loaded into the Arrays before they get returned. Since I am new to swift I am really satisfied with my data model set up to load multiple sections into the tableview and don't want to change everything. The only problem is as I said, that the Firebase data collectors need some kind of a completion handler, but I don't really know how to apply them and I have no idea how to change the following code as well...
This is the class which defines an object:
class Court {
var AnzahlToreKoerbe: String?
var Breitengrad: String?
var Groesse: String?
var Hochgeladen: String?
var Laengengrad: String?
var Stadt: String?
var Stadtteil: String?
var Strasse: String?
var Untergrund: String?
var Upload_Zeitpunkt: Int?
var Platzart: String?
init(AnzahlToreKoerbeString: String, BreitengradString: String, GroesseString: String, HochgeladenString: String, LaengengradString: String, StadtString: String, StadtteilString: String, StrasseString: String, UntergrundString: String, UploadTime: Int, PlatzartString: String) {
AnzahlToreKoerbe = AnzahlToreKoerbeString
Breitengrad = BreitengradString
Groesse = GroesseString
Hochgeladen = HochgeladenString
Laengengrad = LaengengradString
Stadt = StadtString
Stadtteil = StadtteilString
Strasse = StrasseString
Untergrund = UntergrundString
Upload_Zeitpunkt = UploadTime
Platzart = PlatzartString
}
}
This is the class which collects the objects and load them into multiple arrays, which are then called with the getCOurts function in the tableViewController:
class Platzart
{
var Courts: [Court]
var name: String
init(name: String, Courttypes: [Court]) {
Courts = Courttypes
self.name = name
}
class func getCourts() -> [Platzart]
{
return [self.AllSoccer(), self.AllBasketball(), self.Test(), self.Test2()]
}
This is an example private class function which loads the data:
private class func AllSoccer() -> Platzart {
var allSoccer = [Court]()
let databaseref = FIRDatabase.database().reference()
databaseref.child("Court").child("Fußball").observe(.childAdded, with: { (snapshot) in
if let Courtdictionary = snapshot.value as? [String : Any] {
let city = Courtdictionary["Stadt"] as? String
let district = Courtdictionary["Stadtteil"] as? String
let street = Courtdictionary["Strasse"] as? String
let surface = Courtdictionary["Untergrund"] as? String
let latitude = Courtdictionary["Breitengrad"] as? String
let longitude = Courtdictionary["Laengengrad"] as? String
let size = Courtdictionary["Groesse"] as? String
let Userupload = Courtdictionary["Hochgeladen"] as? String
let timestamp = Courtdictionary["Upload_Zeitpunkt"] as? Int
let numberofHoops = Courtdictionary["AnzahlToreKoerbe"] as? String
let courttype = Courtdictionary["Platzart"] as? String
allSoccer.append(Court(AnzahlToreKoerbeString: numberofHoops!, BreitengradString: latitude!, GroesseString: size!, HochgeladenString: Userupload!, LaengengradString: longitude!, StadtString: city!, StadtteilString: district!, StrasseString: street!, UntergrundString: surface!, UploadTime: timestamp!, PlatzartString: courttype!))
print(allSoccer)
}
})
return Platzart(name: "Fußballplatz", Courttypes: allSoccer)
}
The data is then loaded into the tableview:
class CourtlistViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
lazy var Courtarrays: [Platzart] = {
return Platzart.getCourts()
}()
#IBOutlet weak var CourtlisttableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
CourtlisttableView.delegate = self
CourtlisttableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
CourtlisttableView.reloadData()
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let Courttype = Courtarrays[section]
return Courttype.name
}
func numberOfSections(in tableView: UITableView) -> Int {
return Courtarrays.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Courtarrays[section].Courts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = CourtlisttableView.dequeueReusableCell(withIdentifier: "Court Cell", for: indexPath) as! CourtCell
let Platzarray = Courtarrays[indexPath.section]
let Sportplatz = Platzarray.Courts[indexPath.row]
cell.updateUI(Sportplatz)
return cell
}
}
This procedure works well with data which I append to an array manually. For the Firebase Sections (AllSoccer() and AllBasketball()) only the headers are loaded and displayed.
I am creating an inventory app in order to keep track of items held in a laboratory. In the laboratory there are different stations which contain different items in them, which as you can see is structured properly in my Firebase database.
Firebase Database
Iphone Simulator
My problem comes when I try to delete a particular item out of the tableCell. I am able to remove it from the UI but in firebase the data still remains. I have done coutless reserch but am not able to find anything relating to this particular problem.
Data Services Class
let DB_BASE = FIRDatabase.database().reference().child("laboratory") //contains the root of our database
let STORAGE_BASE = FIRStorage.storage().reference()
class DataService {
static let ds = DataService()
//DB References
private var _REF_BASE = DB_BASE
private var _REF_STATION = DB_BASE.child("stations")
private var _REF_USERS = DB_BASE.child("users")
//Storage Reference
private var _REF_ITEM_IMAGE = STORAGE_BASE.child("item-pics")
var REF_BASE: FIRDatabaseReference {
return _REF_BASE
}
var REF_STATION: FIRDatabaseReference {
return _REF_STATION
}
var REF_USERS: FIRDatabaseReference {
return _REF_USERS
}
var REF_ITEM_IMAGES: FIRStorageReference {
return _REF_ITEM_IMAGE
}
//creating a new user into the firebase database
func createFirebaseDBUser(_ uid: String, userData: Dictionary<String, String>) {
REF_USERS.child(uid).updateChildValues(userData)
}
}
Inventory View Controller
import UIKit
import Firebase
class InventoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var items = [Item]()
private var _station: Station!
private var _item: Item!
var sortIndex = 3
var imagePicker: UIImagePickerController!
static var imageCache: NSCache<NSString, UIImage> = NSCache()
var imageSelected = false
#IBOutlet weak var itemImageToAdd: UIImageView!
#IBOutlet weak var objectTextInput: UITextField!
#IBOutlet weak var brandTextInput: UITextField!
#IBOutlet weak var unitTextInput: UITextField!
#IBOutlet weak var amountTextInput: UITextField!
#IBOutlet weak var tableView: UITableView!
#IBOutlet var addItemView: UIView!
#IBOutlet weak var currentStationLabel: UILabel!
var station: Station {
get {
return _station
} set {
_station = newValue
}
}
override func viewDidLoad() {
super.viewDidLoad()
var currentStationName = station.title
currentStationLabel.text = currentStationName
self.items = []
let currentStation = station.title
let stationRef = DataService.ds.REF_STATION.child(currentStation!)
let inventoryRef = stationRef.child("inventory")
tableView.delegate = self
tableView.dataSource = self
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.delegate = self
inventoryRef.observe(.value, with: { (snapshot) in
print(snapshot.value!)
self.items = []
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
print("SNAP: \(snap)")
if let itemDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let item = Item(itemKey: key,
itemData: itemDict)
self.items.append(item)
}
}
}
self.tableView.reloadData()
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "inventoryTableCell", for: indexPath) as? ItemCell {
if let img = InventoryViewController.imageCache.object(forKey: NSString(string: item.imageURL!)) {
cell.updateItemUI(item: item, img: img)
} else {
cell.updateItemUI(item: item)
}
return cell
} else {
return ItemCell()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func postToFirebase(itemImageURL: String) {
let post: Dictionary<String, AnyObject> = [
"objectLabel": objectTextInput.text! as AnyObject,
"brandLabel": brandTextInput.text! as AnyObject,
"unitLabel": unitTextInput.text! as AnyObject,
"amountLabel": amountTextInput.text! as AnyObject,
//post elsewhere as an image for future reference
"itemImageURL": itemImageURL as AnyObject,
]
let stationText = _station.title
let stationRef = DataService.ds.REF_STATION.child(stationText!)
let inventoryRef = stationRef.child("inventory")
let firebasePost = inventoryRef.childByAutoId()
firebasePost.setValue(post)
objectTextInput.text = ""
brandTextInput.text = ""
unitTextInput.text = ""
amountTextInput.text = ""
imageSelected = false
tableView.reloadData()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
itemImageToAdd.image = image
imageSelected = true
} else {
print("Please select a valid image")
}
imagePicker.dismiss(animated: true, completion: nil)
}
#IBAction func backToStations(_ sender: Any) {
performSegue(withIdentifier: "backToStations", sender: nil)
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(tableView: (UITableView!), commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: (NSIndexPath!)) {
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let currentStation = station.title
let stationRef = DataService.ds.REF_STATION.child(currentStation!)
let inventoryRef = stationRef.child("inventory")
var deleteAction = UITableViewRowAction(style: .default, title: "Delete") {action in
//Insert code to delete values from Firebase
self.items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath as IndexPath], with: .fade)
}
var editAction = UITableViewRowAction(style: .normal, title: "Edit") { action in
}
return [deleteAction, editAction]
}
}
My thought process is upon delete to call self_items.key reffering to the current key of the particular tableCell row. From there I would use the current key whick would be the autoID and remove the value that way. Unfortunatly though that crashes the program with a fatal nil error.
The best way I've found to solve this problem is in your delete action, delete the object from Firebase. Do not alter the tableview from here.
Then in your data listener, check when the data comes back as deleted(or NULL), then remove it from the tableview datasource array and update the tableview.
I have an instance where a user picks from a UITable. The selected record has a name and an id associated with it.
At the moment to verify the name and id are being correctly reported I am using
let tempCountryId = (self.newCountries[cellCountryId!])
print (tempCountryId)
Country(name: Optional("England"), countryId: Optional("5"))
I want to be able to store that countryId in a variable so I can repopulate my UITable with data (Football Divisions) that match the countryId '5'
How do I do this?
This is my full script:
import UIKit
class PickTeamViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var teamsTableView: UITableView!
var pickedCountryID: Int?
var selectedCellCountryTitle: String?
var cellCountryId: Int?
struct Country {
var name: String?
var countryId: String?
init(_ dictionary: [String : String]) {
self.name = dictionary["name"]
self.countryId = dictionary["id"]
}
}
struct Divisions {
var divisionName: String?
var divisionId: String?
init(_ dictionary: [String : String]) {
self.divisionName = dictionary["name"]
self.divisionId = dictionary["country_id"]
}
}
struct Teams {
var teamName: String?
var newTeamId: String?
init(_ dictionary: [String : String]) {
self.teamName = dictionary["name"]
}
}
struct TeamId {
var newTeamId: String?
init(_ dictionary: [String : String]) {
self.newTeamId = dictionary["id"]
}
}
var newCountries = [Country]()
var newDivisions = [Divisions]()
var newTeams = [Teams]()
var newTeamId = [TeamId]()
override func viewDidAppear(_ animated: Bool) {
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getTeams.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "GET";
let task = URLSession.shared.dataTask(with: myUrl!) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if error != nil {
print("error=\(error)")
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
print (json)
if let arr = json?["countries"] as? [[String:String]] {
self.newCountries = arr.flatMap { Country($0) }
self.teamsTableView.reloadData()
}
if let arr = json?["divisions"] as? [[String:String]] {
self.newDivisions = arr.flatMap { Divisions($0) }
}
if let arr = json?["teams"] as? [[String:String]] {
self.newTeams = arr.flatMap { Teams($0) }
}
self.teamsTableView.reloadData()
} catch{
print(error)
}
}
}
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.newCountries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let country = newCountries[indexPath.row]
let cell = UITableViewCell()
cell.textLabel?.text = country.name
cell.textLabel?.font = UIFont(name: "Avenir", size: 12)
cell.textLabel?.textColor = UIColor.black
cell.backgroundColor = UIColor.white
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
cellCountryId = indexPath.row
// print (self.newCountries[cellCountryId!])
let tempCountryId = (self.newCountries[cellCountryId!])
print (tempCountryId)
}
override func viewDidLoad() {
super.viewDidLoad()
self.teamsTableView.delegate = self
self.teamsTableView.dataSource = self
// Do any additional setup after loading the view.
}
}
As discussed in the comments you should use another view controller to show the details. In didSelectRowAtIndexPath method take out the selected country from newCountries array and pass it to the DetailViewController.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let countryDetailsVC = self.storyboard?.instantiateViewController(withIdentifier: "CountryDetailsViewController") as! DetailViewController
countryDetailsVC.country = selectedCountry
present(countryDetailsVC, animated: true, completion: nil)
}
Now that you have the country Struct you can show its details in the DetailViewController.
Your table is populated from the array newCountries. So, to replace the contents of the table, you would need to replace the contents of newCountries and reload the table.
But that is not a very wise strategy. It would be better to show a different view controller with a different table and a different data array.