0

I have a TabBar with various Tabs in my RestaurantApp, When I click the addToCart and goes to the CartViewContorller, the added item don't show I have to relaunch the App to see the item there. I have seen similar questions with various answer on this question here but non of the solutions seems to work in my case I don't really know whats wrong. Below is my code for the CartViewContorller I want to reload tableview anytime it is loaded. Thanks all for your help

import UIKit
import Alamofire
import os.log

class CartViewController: UITableViewController {

    var cartData = [CartResponse.Cart]()

    override func viewDidLoad() {
        super.viewDidLoad()

        cart()

        tableView.delegate = self
        tableView.dataSource = self

        let nib = UINib(nibName: "viewCartCell", bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: "cartCustomCell")


        let footerView = UIView()
        footerView.backgroundColor = UIColor.red
        footerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 60)
        tableView.tableFooterView = footerView

    }


    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

       self.tableView.reloadData()
    }


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cartData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell: CartTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cartCustomCell", for: indexPath) as? CartTableViewCell else {
            os_log("Dequeue cell isn't an instance of CustomTableCell", log: .default, type: .debug)
            fatalError()

        }

        cell.recipeNameLbl?.text = cartData[indexPath.row].recipeName
        cell.restaurantNameLbl?.text = cartData[indexPath.row].restaurantName
        cell.addtionalNoteLbl?.text = cartData[indexPath.row].additionalNote
        cell.quantityLbl?.text = cartData[indexPath.row].recipeQuantity
        cell.totalLbl?.text = cartData[indexPath.row].recipePrice
        cell.totalCostLbl?.text = cartData[indexPath.row].totalCost

        return cell
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        guard editingStyle == .delete else {return}

        //getting userId from defaults
        let CartId = cartData[indexPath.row].cartId
        let cartId = CartId

        //creating parameters for the post request
        let parameters: Parameters=[
            "cartId":Int(cartId)
        ]

        //Constant that holds the URL for web service
        let URL_SELECT_FROM_CART = "http://localhost:8888/restaurant/deleteFromCart.php?"

        Alamofire.request(URL_SELECT_FROM_CART, method: .post, parameters: parameters).responseJSON {
            response in
            //printing response
            print(response)
        }

        cartData.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)

    }

    //Fetching from Cart Method
    func cart(){

        //getting userId from defaults
        let defaultValues = UserDefaults.standard
        let userId = defaultValues.string(forKey: "userid")

        //creating parameters for the post request
        let parameters: Parameters=[
            "userId":Int(userId!)!
        ]

        //Constant that holds the URL for web service
        let URL_SELECT_FROM_CART = "http://localhost:8888/restaurant/cart.php?"

        Alamofire.request(URL_SELECT_FROM_CART, method: .post, parameters: parameters).responseJSON {
            (response) in            

            let result = response.data

            do{
                let decoder = JSONDecoder()
                let downloadedCart = try decoder.decode(CartResponse.self, from: result!)
                self.cartData = downloadedCart.cartItem

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }

            }catch {
                print(error)
            }
        }.resume()
    }

}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Samuel Sam
  • 47
  • 7

2 Answers2

0

You can use :

import UserNotifications NotificationCenter.default.post(name: NSNotification.Name(rawValue: "loadCart"), object: nil)

see more in this answer

cs4alhaider
  • 1,318
  • 1
  • 17
  • 26
0

You have to call cart() this method in viewWillAppear instead of calling viewDidload

 override func viewWillAppear(_ animated: Bool) {
    self.cart()
}
chandra1234
  • 357
  • 6
  • 15