I'm making an restaurant app where I have restaurant which contains food. I have the following problem. From each restaurant, I can add food into my shopping cart, but when im trying to swipe left to delete a cell, close the cart and re-enter in the cart, is deleting all the cart, not the cell I have selected for swipping
This is my model :
struct Cart
{
var photoKeyCart: String
var foodCart: String
var priceCart: Int
}
This is the function im using for retrieving the data from Firestore and displaying it into the cart. This function is called in the viewdidload() .
func getCartProducts() {
let db = Firestore.firestore()
let userID = (Auth.auth().currentUser?.uid)!
db.collection("CartDatabase").document(userID).collection("CartItems").getDocuments { (document, error) in
if let error = error {
print(error)
return
} else {
for document in document!.documents {
let data = document.data()
let newEntry = Cart(photoKeyCart: data["photoKeyCart"] as! String, foodCart: data["foodCart"] as! String , priceCart: data["priceCart"] as! Int
)
self.cart.append(newEntry)
}
}
DispatchQueue.main.async {
// self.datas = self.filteredData
self.cartTableView.reloadData()
}
}
}
Viewdidload function :
override func viewDidLoad() {
super.viewDidLoad()
getCartProducts()
let nib = UINib(nibName: "CartTableViewCell", bundle: nil)
cartTableView.register(nib, forCellReuseIdentifier: "CartTableViewCell")
cartTableView.delegate = self
cartTableView.dataSource = self
}
Table view extension :
extension CartViewController: UITableViewDelegate, UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var sum = 0
for item in cart{
sum += item.priceCart
}
priceTotalLabel.text = "\(sum) lei"
return cart.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = cartTableView.dequeueReusableCell(withIdentifier: "CartTableViewCell", for: indexPath) as! CartTableViewCell
let carts = cart[indexPath.row]
let storageRef = Storage.storage().reference()
let photoRef = storageRef.child(carts.photoKeyCart)
cell.foodInCartPrice.text = " \(carts.priceCart) lei "
cell.foodInCartName.text = carts.foodCart
cell.foodInCartImage.sd_setImage(with: photoRef)
cell.foodInCartImage.layer.borderWidth = 1
cell.foodInCartImage.layer.masksToBounds = false
cell.foodInCartImage.layer.borderColor = UIColor.black.cgColor
cell.foodInCartImage.layer.cornerRadius = cell.foodInCartImage.frame.height/2
cell.foodInCartImage.clipsToBounds = true
return cell
}
This is the function im using for swiping left and trying to delete the cell, but it deletes all my cells. I think the problem is that is deleting all the data from the database, and when the function is called, it have nothing to retrieve.
Database used : Tap here
Related
I have a simple app that populates a UITableView based on data inputed in a different ViewController. I am trying to implement the "swipe left to delete"
My problem is that this UITableView is a dropdown table view. That is when I click on one cell of the UITableView the cells open up and show me the internal cells associated with that one cells.
I think I am missing something simple as my code to delete the row does not work, it just throws a SIGBRT error. I think because maybe I trying to remove the wrong array maybe? I think it is messed up because it is a dropdown UITableView, so I am left with a bunch of extra UITableview rows?
Code to added delete button and remove selected row.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
tableViewData.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
Whole code in the UITableViewController is as follows:
import Foundation
import UIKit
private let reuseidentifier = "Cell"
struct cellData {
var opened = Bool()
var title = String()
var exerciseData = [String]()
var repsSetsData = [String]()
}
//here
struct Contact {
var fullname: String
var exercises : [Exercise]
}
class Exercise : NSObject , NSSecureCoding{
static var supportsSecureCoding: Bool = true
var excerciseName: String
var excerciseReps: String
var excerciseSets: String
init(Name : String, Reps : String, Sets : String) {
excerciseName = Name
excerciseReps = Reps
excerciseSets = Sets
}
func encode(with aCoder: NSCoder) {
aCoder.encode(excerciseName, forKey: "excerciseName")
aCoder.encode(excerciseReps, forKey: "excerciseReps")
aCoder.encode(excerciseSets, forKey: "excerciseSets")
}
required convenience init?(coder aDecoder: NSCoder) {
let excerciseName = aDecoder.decodeObject(forKey: "excerciseName") as! String
let excerciseReps = aDecoder.decodeObject(forKey: "excerciseReps") as! String
let excerciseSets = aDecoder.decodeObject(forKey: "excerciseSets") as! String
self.init(Name: excerciseName, Reps: excerciseReps, Sets: excerciseSets)
}
}
class ContactController: UITableViewController {
//new
var tableViewData = [cellData]()
var contacts = [Contact]()
override func viewDidLoad() {
super.viewDidLoad()
//getting data from CoreData
self.contacts = CoreDataManager.sharedInstance.retrieveDataFromCoreData()
tableView.register(UINib(nibName: "ExerciseCell", bundle: nil), forCellReuseIdentifier: "ExerciseCell")
for contact in contacts{
var exerciseData = [String]()
var repsSetsData = [String]()
for exercise in contact.exercises{
let name = exercise.excerciseName
let sets = exercise.excerciseSets
let reps = exercise.excerciseReps
exerciseData.append(name)
repsSetsData.append("Reps: " + reps + " Sets: " + sets)
}
self.tableViewData.append(cellData.init(opened: false, title: contact.fullname, exerciseData:exerciseData, repsSetsData: repsSetsData))
}
self.tableView.reloadData()
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.title = "Workouts"
view.backgroundColor = .white
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseidentifier)
}
#IBAction func handleAddContact(_ sender: Any) {
let controller = AddContactController()
controller.delegate = self
self.present(UINavigationController(rootViewController: controller), animated: true, completion: nil)
}
//UITABLEVIEW
//all new
override func numberOfSections(in tableView: UITableView) -> Int {
//new
return tableViewData.count
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
//new
if tableViewData[section].opened == true {
return tableViewData[section].exerciseData.count + 1
}else {
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseidentifier, for: indexPath)
cell.textLabel?.text = tableViewData[indexPath.section].title
return cell
}else {
//use a different cell identifier if needed
let cell = tableView.dequeueReusableCell(withIdentifier: "ExerciseCell", for: indexPath) as! ExerciseCell
cell.exerciseLabel.text = tableViewData[indexPath.section].exerciseData[indexPath.row - 1]
cell.repsSetsLabel.text = tableViewData[indexPath.section].repsSetsData[indexPath.row - 1]
cell.repsSetsLabel.sizeToFit()
return cell
}
}
//did select row new
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableViewData[indexPath.section].opened == true {
tableViewData[indexPath.section].opened = false
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .none) //play around with animation
}else {
tableViewData[indexPath.section].opened = true
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .none) //play around with animation
}
}
//being able to delete a row
// this method handles row deletion
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// remove the item from the data model
tableViewData.remove(at: indexPath.row)
// delete the table view row
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
//this is an extention to addContactController. this is what happens whent he done button is clicked in addcontactcontroller
extension ContactController: AddContactDelegate {
func addContact(contact: Contact) {
self.dismiss(animated: true) {
//Saving Data to CoreData
CoreDataManager.sharedInstance.addContactsToCoreData(contact: contact)
self.contacts.append(contact)
//Settings values in table view
var exerciseData = [String]()
var repsSetsData = [String]()
for exercise in contact.exercises{
let name = exercise.excerciseName
let sets = exercise.excerciseSets
let reps = exercise.excerciseReps
exerciseData.append(name)
repsSetsData.append("Reps: " + reps + " Sets: " + sets)
}
self.tableViewData.append(cellData.init(opened: false, title: contact.fullname, exerciseData:exerciseData, repsSetsData: repsSetsData))
self.tableView.reloadData()
}
}
}
After deleting the rows can you try to reload the tableview cells like this: self.tableView.reloadData()
It's supposed that you delete a row not an entire section , so replace
tableViewData.remove(at: indexPath.row)
with
tableViewData[indexPath.section].exerciseData.remove(at: indexPath.row)
also make sure exerciseData is mutable ( declared as var )
So I recently asked a question regarding firebase - but have refactored my code quite a bit as I wanted all of my firebase methods to be done in the same place. I am having the following issue after the refactor...
Data from my firebase database is not populating my tableview. I'm not too sure why this would be, as it was working fine before I moved the method to a separate file from my table view(for cleaner code). All I did was move the method that populates the array to a separate file, return an array and then reload the tableview after calling the method. Below is the code in question:
In my FireBaseMethods class
//-------------- POPULATE TABLE ARRAY -----------------//
public func populateConsumableTableArray() -> [Consumable]{
var tableArray = [Consumable]()
//let the object populate itself.
ref.child("Consumables").observe(.childAdded, with: { snapshot in
let dataChange = snapshot.value as? [String:AnyObject]
let aRequest = Consumable(aDict: dataChange!)
tableArray.append(aRequest)
})
return tableArray
}
In my ListOfConsumablesViewController table view class
class ListOfConsumablesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
private var methods:MethodsForController = MethodsForController()
private var fireBaseMethods:FireBaseMethods = FireBaseMethods()
private var consumableArray = [Consumable]()
let picker = UIImagePickerController()
#IBOutlet weak var consumableTable: UITableView!
//-------------------- VIEW DID LOAD -----------------------//
override func viewDidLoad() {
super.viewDidLoad()
//Trying to populate the table view here...
consumableArray = fireBaseMethods.populateConsumableTableArray()
consumableTable.reloadData()
self.consumableTable.dataSource = self
self.consumableTable.delegate = self
}
...
//---------------------- FUNCTIONS FOR TABLE VIEW CELLS & TABLE ----------------------//
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(consumableArray.count)
return consumableArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "consumableCell", for: indexPath) as! ConsumablesCell
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.backgroundColor = UIColor.white
cell.adapterType.text = consumableArray[indexPath.row].getType()
cell.count.text = String(consumableArray[indexPath.row].getCount())
if Int(consumableArray[indexPath.row].getCount()) ?? 0 <= 0{
cell.count.textColor = UIColor.red
}else{
cell.count.textColor = UIColor.black
}
cell.sku.text = consumableArray[indexPath.row].getSku()
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 90
}
}
As shown below, nothing populates in the table view... I'm assuming it's something to do with the method being in a separate file, but I'm not really sure why that would be?
Simple implementation of a completion handler
//-------------- POPULATE TABLE ARRAY -----------------//
public func populateConsumableTableArray(completion: #escaping (Consumable) -> Void) {
//let the object populate itself.
ref.child("Consumables").observe(.childAdded, with: { snapshot in
guard let dataChange = snapshot.value as? [String:AnyObject] else { return }
let aRequest = Consumable(aDict: dataChange)
completion(aRequest)
})
}
override func viewDidLoad() {
super.viewDidLoad()
self.consumableTable.dataSource = self
self.consumableTable.delegate = self
//Trying to populate the table view here...
fireBaseMethods.populateConsumableTableArray { [unowned self] consumable in
self.tableArray.append(consumable)
DispatchQueue.main.async {
self.consumableTable.reloadData()
}
}
}
I have ran into a very interesting problem in my application. Upon viewing the users profile page the data in my tableview is being pulled and printed into the console, the problem though is that my information will not load into my tablecell.
If i were to leave the current tab and then go back to the profile page my data will then be loaded. I am using firebase in order to pull my information down.
I would like for the data to be there upon the first time viewing the page.
ProfileViewController
var cellId = "cell"
var userGames = [Game]()
var userCurrentGames = [Any]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(ProfileGameCell.self, forCellReuseIdentifier: cellId)
//I CALL MY FUNCTIONS UPON FIRST LOAD
getCurrentUser()
getUsersGames()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//I CALL FUCTIONS EVERY TIME THE VIEW LOADS INCASE DATA CHANGES
getCurrentUser()
getUsersInformation()
getUsersGames()
}
func getUsersGames() {
let ref = Database.database().reference()
let current = getCurrentUser()
//I FIND ALL THE GAMES IN THE USERS REF AND APPEND THEIR KEY TO THE ARRAY
ref.child("users").child(current).child("user games").observe(.value, with: {(snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
self.userCurrentGames = []
for snap in snapshot {
let gameKey = snap.key
print("SNAPSHOT DATAAA: \(gameKey)")
self.userCurrentGames.append(gameKey)
}
}
})
displayUsersGames()
}
func displayUsersGames() {
let ref = Database.database().reference()
self.userGames = []
//I FIND ALL THE GAMES AND APPEND THEM TO THE ACTUAL GAME ARRAY
for i in userCurrentGames {
ref.child("games").child("\(i)").observeSingleEvent(of: .value, with: { (gameSnap) in
if let gameDict = gameSnap.value as? Dictionary<String, AnyObject> {
let key = gameSnap.key
let game = Game(postKey: key, gameData: gameDict)
self.userGames.append(game)
self.tableView.reloadData()
}
})
}
}
Table View Functions
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let game = userGames[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? ProfileGameCell {
cell.adminButton.tag = indexPath.row
cell.configureUserGameCell(game: game)
return cell
} else {
return ProfileGameCell()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userGames.count
}
The problem is very clear:
observe works asynchronously – the result is returned later – so userCurrentGames is empty when displayUsersGames() is called.
A solution is to move displayUsersGames() into the completion block
...
ref.child("users").child(current).child("user games").observe(.value, with: {(snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
self.userCurrentGames = []
for snap in snapshot {
let gameKey = snap.key
print("SNAPSHOT DATAAA: \(gameKey)")
self.userCurrentGames.append(gameKey)
}
self.displayUsersGames()
}
})
Note:
Force downcast the cell
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! ProfileGameCell
The code must not crash. If it does it reveals a design error.
I have been trying to create an app that gets a website data through a function ( func obtainData) and display some of the data on a tableView.
I have figured out the part on how to get the data from the website then make it as an array so I can use indexpath.row but I have not able to find out the way to pass on the data I'm getting to display it on a tableView.
Any ideas!
Thanks
Below is the code I wrote.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var recommendation = ""
var recommendationArray = ""
var delExtraTextArray = [String]()
var urlRecommendationArrayStart = [String]()
var urlRecommendationArrayEnd = [String]()
var RecommendationStart = [String]()
var RecommendationEnd = [String]()
// need the var below to make the recommendations as an array to be used in a table view as indexpath.row
var cellNumber = [String]()
var cellTitle = [String]()
var cellDetails = [String]()
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
obtainData()
tableView.delegate = self
tableView.dataSource = self
}
func obtainData () {
var url = NSURL (string: "http://www.choosingwisely.org/societies/american-college-of-obstetricians-and-gynecologists")
if url != nil {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error == nil {
// to get all of the url content and covert them into string
var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding) as NSString!
// to get to a specific contect seperated by a string
self.urlRecommendationArrayStart = (urlContent?.componentsSeparatedByString("<ol class=\"society-ol\">"))!
if self.urlRecommendationArrayStart.count > 0 {
self.urlRecommendationArrayEnd = self.urlRecommendationArrayStart[1].componentsSeparatedByString("</ol>")
// print(self.urlRecommendationArrayEnd)
// to check if there is any extra not needed text at the end of the recommnedations in the source page
self.delExtraTextArray = self.urlRecommendationArrayEnd[0].componentsSeparatedByString("<p><a")
if self.delExtraTextArray.count > 0 {
self.recommendationArray self.delExtraTextArray[0] as! String
self.obtainRecommendationTitle()
} else {
self.recommendationArray = self.urlRecommendationArrayEnd[0] as! String
self.obtainRecommendationTitle()
// print("method 2 worked")
}
} else {
self.textView.text = "Sorry, couldn't get the recommendation at this point. Please make sure to download the updated version of the app"
}
} else {
self.textView.text = "Please check connection then try again"
}
})
task.resume()
} else {
self.textView.text = "Please check connection then try again"
}
}
// to get the title of each recommendation
func obtainRecommendationTitle() -> Array<String> {
for var i = 2; i < urlRecommendationArrayEnd[0].componentsSeparatedByString("<p>").count - delExtraTextArray.count ; i = i + 4 {
self.RecommendationStart = self.delExtraTextArray[0].componentsSeparatedByString("<p>")
self.RecommendationEnd = RecommendationStart[i].componentsSeparatedByString("</p>")
self.recommendationArray = self.RecommendationEnd[0] as! String
self.cellTitle.append(recommendationArray)
}
return cellTitle
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellTitle.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
cell.textLabel?.text = cellTitle [indexPath.row]
return cell
}
You would pass it via the cellForRowAtIndexPath delegate method. This question is too open ended for a firm answer, but following along any half-decent online UITableView tutorial should do the trick.
A quick glance at this one appears to hit the basics: https://www.weheartswift.com/how-to-make-a-simple-table-view-with-ios-8-and-swift/
I think what you need is to configure the contents of the table view cell with the data you want. Based on this assumption, you can use something like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("PUT_YOUR_CELL_IDENTIFIER_HERE") as? UITableViewCell {
let stuff = yourArray[indexPath.row]
stuff.some_property_you_want = the_value_you_want
return cell
} else {
return UITableViewCell()
}
}
If you show some code or explain your problem a little better, you will get a better support from the people here on Stack Overflow.
EDIT (based on your edit):
Are you using a normal cell?
The cell has the text field to put the string you want?
Did you define the cell's identifier, "cell", in the storyboard?
Did you connect the tableView outlet to the tableView itself?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell {
print("ENTERED HERE!")
let myCellText = cellTitle[indexPath.row]
//what is the result of this print?
print("TEXT TO ADD: \(myCellText)")
//(...)
cell.textLabel?.text = myCellText
return cell
} else {
return UITableViewCell()
}
}
What is the result of these prints?
I am running into difficulty displaying the data from the query I made in the individual cells of my tableview. I believe that my logic is correct, but I'm not seeing the console.log's that I am calling within my function that contains the Parse queried data. This might be a simple fix, but it isn't coming to me at the moment. The console log I should be seeing to validate that my query is coming through correctly is the println("\(objects.count) users are listed"), it should then be displayed within the usernameLabel.text property.
import UIKit
class SearchUsersRegistrationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var userArray : NSMutableArray = []
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
loadParseData()
}
func loadParseData() {
var query : PFQuery = PFUser.query()
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]!, error:NSError!) -> Void in
if error == nil {
if let objects = objects {
println("\(objects.count) users are listed")
for object in objects {
self.userArray.addObject(object)
}
self.tableView.reloadData()
}
} else {
println("There is an error")
}
}
}
let textCellIdentifier = "Cell"
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.userArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! SearchUsersRegistrationTableViewCell
let row = indexPath.row
let cellDataParse : PFObject = self.userArray.objectAtIndex(row) as! PFObject
//cell.userImage.image = UIImage(named: usersArr[row])
cell.usernameLabel.text = cellDataParse.objectForKey("_User") as! String
return cell
}
}
I fixed the issue. I needed to cast the index path row in the users array as a PFUser and then cast the user's username property as a String and then set that as the label text.
let row = indexPath.row
var user = userArray[row] as! PFUser
var username = user.username as String
cell.usernameLabel.text = username