Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @IBAction func addToCart(_ sender: UIBarButtonItem) {
- let itemToAdd = product
- let existingIndex = cart.containsAtIndex(product!)
- // If item from catalogue exist in cart, then modify
- if (existingIndex >= 0) {
- cart.changeItem(existingIndex, newItem: itemToAdd!)
- modifyCart(product: itemToAdd!)
- }
- // If item is not found in cart, then add a new one
- else {
- let storyboard = UIStoryboard(name: "Main", bundle: nil)
- if let controller = storyboard.instantiateViewController(withIdentifier: "CartTableView") as? CartTableViewController {
- let newIndexPath = IndexPath(row: cart.numberOfItems(), section: 0)
- cart.addItem(itemToAdd!)
- controller.tableView.insertRows(at: [newIndexPath], with: .automatic)
- saveToCart(product: itemToAdd!, update: true)
- }
- }
- self.navigationController?.popViewController(animated: true)
- self.dismiss(animated: true, completion: nil)
- }
- private func saveToCart(product: Product, update: Bool) {
- let realm = try! Realm()
- print(product)
- try! realm.write {
- realm.add(product, update: true)
- }
- }
- private func modifyCart(product: Product) {
- let prodName = product.itemName
- let realm = try! Realm()
- try! realm.write {
- let item = realm.objects(Product.self).filter("itemName = %@", prodName).first
- item!.quantity = product.quantity
- }
- }
- class Cart: NSObject {
- static let myCart = Cart()
- private var products: [Product]
- private override init() {
- self.products = []
- }
- func getCartItems() -> [Product] {
- return products
- }
- func getItem(_ index: Int) -> Product? {
- if products.indices.contains(index) {
- return products[index]
- } else {
- return nil
- }
- }
- func addItem(_ item: Product) {
- products.append(item)
- }
- func removeItem(_ index: Int) {
- products.remove(at: index)
- }
- func numberOfItems() -> Int {
- return products.count
- }
- func changeItem(_ index: Int, newItem: Product) {
- if products.indices.contains(index) {
- products[index] = newItem
- }
- }
- func containsAtIndex(_ item: Product) -> Int {
- for i in (0..<products.count) {
- if (products[i].itemName == item.itemName) {
- return i
- }
- }
- return -1
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement