Advertisement
goodboy_html

CartController

Jul 17th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 15.56 KB | None | 0 0
  1. //
  2. //  CartController.swift
  3. //  PeriplusApp
  4. //
  5. //  Created by Muhammad Husain on 7/18/17.
  6. //  Copyright © 2017 Muhammad Husain All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import CoreData
  11. import Alamofire
  12.  
  13. class CartController : BaseViewController {
  14.     // MARK: Properties
  15.     @IBOutlet weak var priceLabel: UILabel!
  16.     @IBOutlet weak var checkoutButton: UIButton!
  17.     @IBOutlet weak var tableView: UITableView!
  18.     @IBOutlet weak var emptyCartImageView: UIImageView!
  19.     @IBOutlet weak var deleteAllButton: UIBarButtonItem!
  20.     var price : Double = 0
  21.     var index : Int = 0
  22.     var productDetail : [ProductDetail] = []
  23.     var productList : [NSManagedObject] = []
  24.     var productUpdate : [Double] = []
  25.     var url : [String] = []
  26.     var count: Int = 0
  27.    
  28.    
  29.    
  30.     // MARK: General
  31.     override func setView() {
  32.         super.setView()
  33.         showProgressView()
  34.         setupLayout()
  35.         fetchCoreData()
  36.         //self.navigationController?.navigationBar.topItem?.title = ""
  37.        
  38.     }
  39.    
  40.     // MARK: Actions
  41.  
  42.     @IBAction func deleteAll(_ sender: Any) {
  43.         if productList.count != 0 {
  44.             showCustomAlert("Confirmation", "Ok", "Cancel", "All data will be lost.","DeleteAll")
  45.         } else {
  46.             showAlert("Information", "You dont have any product on your cart")
  47.         }
  48.     }
  49.    
  50.     override func alertActionAgree(_ status: String) {
  51.         if status == "DeleteAll" {
  52.             self.deleteAllDataCore()
  53.         }
  54.         if status == "Login" {
  55.             self.showLoginScreen()
  56.         }
  57.     }
  58.    
  59.     override func alertActionAgree(_ status: String, _ index: Int) {
  60.         if status == "RemoveProduct" {
  61.             self.deleteProduct(index: index)
  62.         }
  63.     }
  64.    
  65.     func fetchCoreData() {
  66.         self.price = 0
  67.         self.index = 0
  68.         self.productDetail.removeAll()
  69.         self.url.removeAll()
  70.         guard let appDelegate =
  71.             UIApplication.shared.delegate as? AppDelegate else {
  72.                 return
  73.         }
  74.         let managedContext =
  75.             appDelegate.persistentContainer.viewContext
  76.        
  77.         let fetchRequest =
  78.             NSFetchRequest<NSManagedObject>(entityName: "ProductList")
  79.        
  80.         do {
  81.             productList = try managedContext.fetch(fetchRequest)
  82.             if productList.count != 0 {
  83.                 self.emptyCartImageView.isHidden = true
  84.                 for i in 0..<productList.count{
  85.                     if isLogin() {
  86.                          self.url.append("\(url_productdetail2)&product_id=\(productList[i].value(forKey: "product_id") as! String)")
  87.                     } else {
  88.                          self.url.append("\(url_productdetail)&product_id=\(productList[i].value(forKey: "product_id") as! String)")
  89.                     }
  90.                    
  91.                 }
  92.                 setupJSON()
  93.             }
  94.             else {
  95.                 self.hideProgressView()
  96.                 self.emptyCartImageView.isHidden = false
  97.                 self.priceLabel.backgroundColor = UIColor.white
  98.                 self.priceLabel.isHidden = true
  99.                 self.deleteAllButton.isEnabled = false
  100.                 self.checkoutButton.isHidden = true
  101.             }
  102.         } catch let error as NSError {
  103.             print("Could not fetch. \(error), \(error.userInfo)")
  104.         }
  105.         self.tableView.reloadData()
  106.     }
  107.    
  108.     func updateQuantity (id:String, quantity:Int, index:Int) {
  109.         guard let appDelegate =
  110.             UIApplication.shared.delegate as? AppDelegate else {
  111.                 return
  112.         }
  113.        
  114.         let managedContext =
  115.             appDelegate.persistentContainer.viewContext
  116.        
  117.         let fetchRequest =
  118.             NSFetchRequest<NSManagedObject>(entityName: "ProductList")
  119.        
  120.         do {
  121.             productList = try managedContext.fetch(fetchRequest)
  122.             let product = productList[index]
  123.             product.setValue(id, forKey: "product_id")
  124.             product.setValue(quantity, forKey: "quantity")
  125.  
  126.             do {
  127.                 try managedContext.save()
  128.             } catch let error as NSError  {
  129.                 print("Could not save \(error), \(error.userInfo)")
  130.             }
  131.         } catch let error as NSError {
  132.             print("Could not fetch. \(error), \(error.userInfo)")
  133.         }
  134.     }
  135.    
  136.     func priceStringToDouble(price : String) -> Double {
  137.         let a = price.replacingOccurrences(of: "Rp ", with: "", options: .literal, range: nil)
  138.         let b : Double = Double(a.replacingOccurrences(of: ",0", with: "0", options: .literal, range: nil))!
  139.        
  140.         return b
  141.     }
  142.    
  143.     func setupJSON() {
  144.         Alamofire.request(self.url[index]).responseJSON { response in
  145.             switch (response.result) {
  146.             case .success:
  147.                 guard let product = response.result.value as? [NSDictionary] else {
  148.                     print("didn't get todo object as JSON from API")
  149.                     print("Error: \(String(describing: response.result.error))")
  150.                     return
  151.                 }
  152.              
  153.                 self.productDetail.append(ProductDetail(dictionary: product[0])!)
  154.                 if self.productDetail.count == self.productList.count {
  155.                     for i in 0..<self.productDetail.count{
  156.                        
  157.                         if self.productDetail[i].special != "" &&  self.productDetail[i].special != nil {
  158.                             let a = Double(self.productDetail[i].special!)!
  159.                             let qtty = self.productList[i].value(forKey: "quantity") as! Int
  160.                             self.productUpdate.append(a)
  161.                             self.price = self.price + (a * Double(qtty))
  162.                         } else if self.productDetail[i].price_asli != "" &&  self.productDetail[i].price_asli != nil {
  163.                             let a = Double(self.productDetail[i].price_asli!)!
  164.                             let qtty = self.productList[i].value(forKey: "quantity") as! Int
  165.                             self.productUpdate.append(a)
  166.                             self.price = self.price + (a * Double(qtty))
  167.                            
  168.                         }
  169.                     }
  170.                 }
  171.                
  172.                
  173.                 self.index = self.index+1
  174.                
  175.                 if self.index < self.url.count {
  176.                     self.setupJSON()
  177.                 }
  178.                 else {
  179.                     self.hideProgressView()
  180.                     self.priceLabel.text = "Total: Rp. " + String.localizedStringWithFormat("%.0f", self.price)
  181.                     self.tableView.reloadData()
  182.                 }
  183.                 break
  184.             case .failure(let error):
  185.                 self.hideProgressView()
  186.                 if error._code == NSURLErrorTimedOut {
  187.                     //HANDLE TIMEOUT HERE
  188.                     self.showAlert("Alert", "Connection Problem: Request time out")
  189.                 }
  190.                 print("\n\nAuth request failed with error:\n \(error)")
  191.                 break
  192.             }
  193.         }
  194.     }
  195.    
  196.     func deleteAllDataCore() {
  197.         let delegate = UIApplication.shared.delegate as! AppDelegate
  198.         let context = delegate.persistentContainer.viewContext
  199.        
  200.         let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "ProductList")
  201.         let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
  202.        
  203.         do {
  204.             try context.execute(deleteRequest)
  205.             try context.save()
  206.         }
  207.         catch {
  208.             print ("There was an error")
  209.         }
  210.         fetchCoreData()
  211.     }
  212.    
  213.     @IBAction func checkoutClick(_ sender: Any) {
  214.         checkSession()
  215.     }
  216.    
  217.     func checkSession() {
  218.         let getUserID = UserDefaults.standard.string(forKey: "customer_id")
  219.        
  220.         if getUserID != nil {
  221.             let vc = storyboard?.instantiateViewController(withIdentifier: "Checkout") as! CheckoutController
  222.             vc.hidesBottomBarWhenPushed = true
  223.             self.navigationController?.pushViewController(vc, animated: true)
  224.         } else {
  225.             self.showCustomAlert("Information", "Login", "Cancel", "You should login if you want to order", "Login")
  226.         }
  227.     }
  228.     func showLoginScreen() {
  229.         let vc = storyboard?.instantiateViewController(withIdentifier: "Login") as! LoginAccountController
  230.         vc.status = true
  231.         let navController = UINavigationController(rootViewController: vc)
  232.         self.present(navController, animated:false, completion: nil)
  233.     }
  234.    
  235.     func deleteProduct(index: Int) {
  236.         guard let appDelegate =
  237.             UIApplication.shared.delegate as? AppDelegate else {
  238.                 return
  239.         }
  240.        
  241.         let managedContext =
  242.             appDelegate.persistentContainer.viewContext
  243.        
  244.         managedContext.delete(productList[index])
  245.         do {
  246.             try managedContext.save()
  247.             productList.remove(at: index)
  248.             fetchCoreData()
  249.         }
  250.         catch let error as NSError {
  251.             print("Error While Deleting Note: \(error.userInfo)")
  252.         }
  253.     }
  254.    
  255.     @IBAction func deleteButtonClick(_ sender: UIButton) {
  256.         showCustomAlert("Confirmation", "Yes", "No", "Are you sure to remove product from cart?", "RemoveProduct", sender.tag)
  257.     }
  258.    
  259.    
  260.     //    func deleteAddress(index: Int) {
  261. //        showProgressView()
  262. //        var parameters = [String:Any]()
  263. //        parameters["address_id"] = address[index].address_id
  264. //        parameters["customer_id"] = self.userId
  265. //        parameters["key_id"] = self.keyId
  266. //        //        requestPOST("\(url_getaddress)delete&customer_id=\(getUserId())&address_id=\((address[index].address_id)!)")
  267. //        requestPOST("\(url_deleteaddress)",parameters)
  268. //    }
  269.    
  270.     // onprogress
  271.     func getTotalPrice(index: Int, quantity: Int, price: Double) -> Double {
  272.         productUpdate[index] = Double(quantity) * price
  273.         var total : Double = 0
  274.         for i in 0..<productUpdate.count {
  275.             total = total + productUpdate[i]
  276.         }
  277.         return total
  278.     }
  279.    
  280.     // MARK: Utilities
  281.     func setupLayout(){
  282.         self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
  283.         self.checkoutButton.tintColor = UIColor(hex: "009499")
  284.         self.navigationController?.navigationBar.tintColor = UIColor.white
  285.         self.navigationController?.navigationBar.barTintColor = UIColor(hex: "009499")
  286.         self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName :UIColor.white]
  287.     }
  288.    
  289.    
  290.    
  291.     @IBAction func imageButtonClick(_ sender: UIButton) {
  292.             let vc = storyboard?.instantiateViewController(withIdentifier: "Promo") as! ProductDetailController
  293.             if isLogin(){
  294.                 vc.url = "\(url_productdetail2)&product_id=\(productDetail[sender.tag].product_id ?? "")"
  295.             } else {
  296.                 vc.url = "\(url_productdetail)&product_id=\(productDetail[sender.tag].product_id ?? "")"
  297.             }
  298.             vc.hidesBottomBarWhenPushed = true
  299.         self.navigationController?.pushViewController(vc, animated: false)
  300.     }
  301. }
  302.  
  303.  
  304. extension CartController: UITableViewDelegate {
  305.     // Override to support editing the table view.
  306.     func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
  307.         if editingStyle == .delete {
  308.             guard let appDelegate =
  309.                 UIApplication.shared.delegate as? AppDelegate else {
  310.                     return
  311.             }
  312.            
  313.             let managedContext =
  314.                 appDelegate.persistentContainer.viewContext
  315.            
  316.             managedContext.delete(productList[indexPath.row])
  317.             productDetail.remove(at: indexPath.row)
  318.             do {
  319.                 try managedContext.save()
  320.             }
  321.             catch let error as NSError {
  322.                 print("Error While Deleting Note: \(error.userInfo)")
  323.             }
  324.             tableView.deleteRows(at: [indexPath], with: .left)
  325.             fetchCoreData()
  326.         }
  327.     }
  328.    
  329.     func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
  330.         return true
  331.     }
  332.    
  333.     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  334.         let item = productDetail[indexPath.row]
  335.         let vc = storyboard?.instantiateViewController(withIdentifier: "Cart") as! ProductDetailController
  336.         vc.url = "\(url_productdetail)&product_id=\(String(describing: item.product_id!))"
  337.         vc.hidesBottomBarWhenPushed = true
  338.         self.navigationController?.pushViewController(vc, animated: false)
  339.     }
  340. }
  341.  
  342. extension CartController: UITableViewDataSource {
  343.     public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  344.         let cell: CartCell = tableView.dequeueReusableCell(withIdentifier: "cartCell") as! CartCell
  345. //        let cell: TestCell = tableView.dequeueReusableCell(withIdentifier: "TestCell") as! TestCell
  346.         let item = productList[indexPath.row]
  347.         count = productList.count
  348.         cell.quantity = item.value(forKey: "quantity") as! Int
  349.         if productList.count == productDetail.count {
  350.             cell.cartTitleLabel.text = productDetail[indexPath.row].name
  351.             cell.cartPriceLabel.text = productDetail[indexPath.row].price
  352. //            let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.tappedMe))
  353. //
  354. //            cell.cartImageView.addGestureRecognizer(tap)
  355.            
  356.            
  357.             cell.cartQuantityNumberLabel.text = String(cell.quantity)
  358.             let current_quantity = cell.quantity
  359.            
  360.             if productDetail[indexPath.row].image != nil {
  361.                 let url = URL(string: productDetail[indexPath.row].image!)
  362.                 let data = try? Data(contentsOf: url!)
  363.                 if data != nil {
  364.                     cell.imageButton.setImage(UIImage(data: data!), for: .normal)
  365. //                    cell.cartImageView.image = UIImage(data: data!)
  366.                 }
  367.                 else {
  368.                     cell.imageButton.setImage(#imageLiteral(resourceName: "default_image"), for: .normal)}
  369. //                    cell.cartImageView.image = #imageLiteral(resourceName: "default_image") }
  370.             } else {
  371.                 cell.imageButton.setImage(#imageLiteral(resourceName: "default_image"), for: .normal)
  372. //                cell.cartImageView.image = #imageLiteral(resourceName: "default_image")
  373.             }
  374.            
  375.             DispatchQueue.main.async {
  376.                 if current_quantity != cell.quantity {
  377.                     self.updateQuantity(id: item.value(forKey: "product_id") as! String, quantity: cell.quantity, index: indexPath.row)
  378.                     self.fetchCoreData()
  379.                 }
  380.                 self.tableView.reloadData()
  381.             }
  382.            
  383.             cell.imageButton.tag = indexPath.row
  384.             cell.imageButton.addTarget(self, action: #selector(imageButtonClick(_:)), for: .touchUpInside)
  385.            
  386.             cell.deleteButton.tag = indexPath.row
  387.             cell.deleteButton.addTarget(self, action: #selector(deleteButtonClick(_:)), for: .touchUpInside)
  388.         }
  389.        
  390.         cell.backgroundColor = UIColor.clear
  391.         return cell
  392.     }
  393.    
  394.    
  395.    
  396.     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  397.         return productList.count
  398.     }
  399.    
  400. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement