Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // CartController.swift
- // PeriplusApp
- //
- // Created by Muhammad Husain on 7/18/17.
- // Copyright © 2017 Muhammad Husain All rights reserved.
- //
- import UIKit
- import CoreData
- import Alamofire
- class CartController : BaseViewController {
- // MARK: Properties
- @IBOutlet weak var priceLabel: UILabel!
- @IBOutlet weak var checkoutButton: UIButton!
- @IBOutlet weak var tableView: UITableView!
- @IBOutlet weak var emptyCartImageView: UIImageView!
- @IBOutlet weak var deleteAllButton: UIBarButtonItem!
- var price : Double = 0
- var index : Int = 0
- var productDetail : [ProductDetail] = []
- var productList : [NSManagedObject] = []
- var productUpdate : [Double] = []
- var url : [String] = []
- var count: Int = 0
- // MARK: General
- override func setView() {
- super.setView()
- showProgressView()
- setupLayout()
- fetchCoreData()
- //self.navigationController?.navigationBar.topItem?.title = ""
- }
- // MARK: Actions
- @IBAction func deleteAll(_ sender: Any) {
- if productList.count != 0 {
- showCustomAlert("Confirmation", "Ok", "Cancel", "All data will be lost.","DeleteAll")
- } else {
- showAlert("Information", "You dont have any product on your cart")
- }
- }
- override func alertActionAgree(_ status: String) {
- if status == "DeleteAll" {
- self.deleteAllDataCore()
- }
- if status == "Login" {
- self.showLoginScreen()
- }
- }
- override func alertActionAgree(_ status: String, _ index: Int) {
- if status == "RemoveProduct" {
- self.deleteProduct(index: index)
- }
- }
- func fetchCoreData() {
- self.price = 0
- self.index = 0
- self.productDetail.removeAll()
- self.url.removeAll()
- guard let appDelegate =
- UIApplication.shared.delegate as? AppDelegate else {
- return
- }
- let managedContext =
- appDelegate.persistentContainer.viewContext
- let fetchRequest =
- NSFetchRequest<NSManagedObject>(entityName: "ProductList")
- do {
- productList = try managedContext.fetch(fetchRequest)
- if productList.count != 0 {
- self.emptyCartImageView.isHidden = true
- for i in 0..<productList.count{
- if isLogin() {
- self.url.append("\(url_productdetail2)&product_id=\(productList[i].value(forKey: "product_id") as! String)")
- } else {
- self.url.append("\(url_productdetail)&product_id=\(productList[i].value(forKey: "product_id") as! String)")
- }
- }
- setupJSON()
- }
- else {
- self.hideProgressView()
- self.emptyCartImageView.isHidden = false
- self.priceLabel.backgroundColor = UIColor.white
- self.priceLabel.isHidden = true
- self.deleteAllButton.isEnabled = false
- self.checkoutButton.isHidden = true
- }
- } catch let error as NSError {
- print("Could not fetch. \(error), \(error.userInfo)")
- }
- self.tableView.reloadData()
- }
- func updateQuantity (id:String, quantity:Int, index:Int) {
- guard let appDelegate =
- UIApplication.shared.delegate as? AppDelegate else {
- return
- }
- let managedContext =
- appDelegate.persistentContainer.viewContext
- let fetchRequest =
- NSFetchRequest<NSManagedObject>(entityName: "ProductList")
- do {
- productList = try managedContext.fetch(fetchRequest)
- let product = productList[index]
- product.setValue(id, forKey: "product_id")
- product.setValue(quantity, forKey: "quantity")
- do {
- try managedContext.save()
- } catch let error as NSError {
- print("Could not save \(error), \(error.userInfo)")
- }
- } catch let error as NSError {
- print("Could not fetch. \(error), \(error.userInfo)")
- }
- }
- func priceStringToDouble(price : String) -> Double {
- let a = price.replacingOccurrences(of: "Rp ", with: "", options: .literal, range: nil)
- let b : Double = Double(a.replacingOccurrences(of: ",0", with: "0", options: .literal, range: nil))!
- return b
- }
- func setupJSON() {
- Alamofire.request(self.url[index]).responseJSON { response in
- switch (response.result) {
- case .success:
- guard let product = response.result.value as? [NSDictionary] else {
- print("didn't get todo object as JSON from API")
- print("Error: \(String(describing: response.result.error))")
- return
- }
- self.productDetail.append(ProductDetail(dictionary: product[0])!)
- if self.productDetail.count == self.productList.count {
- for i in 0..<self.productDetail.count{
- if self.productDetail[i].special != "" && self.productDetail[i].special != nil {
- let a = Double(self.productDetail[i].special!)!
- let qtty = self.productList[i].value(forKey: "quantity") as! Int
- self.productUpdate.append(a)
- self.price = self.price + (a * Double(qtty))
- } else if self.productDetail[i].price_asli != "" && self.productDetail[i].price_asli != nil {
- let a = Double(self.productDetail[i].price_asli!)!
- let qtty = self.productList[i].value(forKey: "quantity") as! Int
- self.productUpdate.append(a)
- self.price = self.price + (a * Double(qtty))
- }
- }
- }
- self.index = self.index+1
- if self.index < self.url.count {
- self.setupJSON()
- }
- else {
- self.hideProgressView()
- self.priceLabel.text = "Total: Rp. " + String.localizedStringWithFormat("%.0f", self.price)
- self.tableView.reloadData()
- }
- break
- case .failure(let error):
- self.hideProgressView()
- if error._code == NSURLErrorTimedOut {
- //HANDLE TIMEOUT HERE
- self.showAlert("Alert", "Connection Problem: Request time out")
- }
- print("\n\nAuth request failed with error:\n \(error)")
- break
- }
- }
- }
- func deleteAllDataCore() {
- let delegate = UIApplication.shared.delegate as! AppDelegate
- let context = delegate.persistentContainer.viewContext
- let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "ProductList")
- let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
- do {
- try context.execute(deleteRequest)
- try context.save()
- }
- catch {
- print ("There was an error")
- }
- fetchCoreData()
- }
- @IBAction func checkoutClick(_ sender: Any) {
- checkSession()
- }
- func checkSession() {
- let getUserID = UserDefaults.standard.string(forKey: "customer_id")
- if getUserID != nil {
- let vc = storyboard?.instantiateViewController(withIdentifier: "Checkout") as! CheckoutController
- vc.hidesBottomBarWhenPushed = true
- self.navigationController?.pushViewController(vc, animated: true)
- } else {
- self.showCustomAlert("Information", "Login", "Cancel", "You should login if you want to order", "Login")
- }
- }
- func showLoginScreen() {
- let vc = storyboard?.instantiateViewController(withIdentifier: "Login") as! LoginAccountController
- vc.status = true
- let navController = UINavigationController(rootViewController: vc)
- self.present(navController, animated:false, completion: nil)
- }
- func deleteProduct(index: Int) {
- guard let appDelegate =
- UIApplication.shared.delegate as? AppDelegate else {
- return
- }
- let managedContext =
- appDelegate.persistentContainer.viewContext
- managedContext.delete(productList[index])
- do {
- try managedContext.save()
- productList.remove(at: index)
- fetchCoreData()
- }
- catch let error as NSError {
- print("Error While Deleting Note: \(error.userInfo)")
- }
- }
- @IBAction func deleteButtonClick(_ sender: UIButton) {
- showCustomAlert("Confirmation", "Yes", "No", "Are you sure to remove product from cart?", "RemoveProduct", sender.tag)
- }
- // func deleteAddress(index: Int) {
- // showProgressView()
- // var parameters = [String:Any]()
- // parameters["address_id"] = address[index].address_id
- // parameters["customer_id"] = self.userId
- // parameters["key_id"] = self.keyId
- // // requestPOST("\(url_getaddress)delete&customer_id=\(getUserId())&address_id=\((address[index].address_id)!)")
- // requestPOST("\(url_deleteaddress)",parameters)
- // }
- // onprogress
- func getTotalPrice(index: Int, quantity: Int, price: Double) -> Double {
- productUpdate[index] = Double(quantity) * price
- var total : Double = 0
- for i in 0..<productUpdate.count {
- total = total + productUpdate[i]
- }
- return total
- }
- // MARK: Utilities
- func setupLayout(){
- self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
- self.checkoutButton.tintColor = UIColor(hex: "009499")
- self.navigationController?.navigationBar.tintColor = UIColor.white
- self.navigationController?.navigationBar.barTintColor = UIColor(hex: "009499")
- self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName :UIColor.white]
- }
- @IBAction func imageButtonClick(_ sender: UIButton) {
- let vc = storyboard?.instantiateViewController(withIdentifier: "Promo") as! ProductDetailController
- if isLogin(){
- vc.url = "\(url_productdetail2)&product_id=\(productDetail[sender.tag].product_id ?? "")"
- } else {
- vc.url = "\(url_productdetail)&product_id=\(productDetail[sender.tag].product_id ?? "")"
- }
- vc.hidesBottomBarWhenPushed = true
- self.navigationController?.pushViewController(vc, animated: false)
- }
- }
- extension CartController: UITableViewDelegate {
- // Override to support editing the table view.
- func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
- if editingStyle == .delete {
- guard let appDelegate =
- UIApplication.shared.delegate as? AppDelegate else {
- return
- }
- let managedContext =
- appDelegate.persistentContainer.viewContext
- managedContext.delete(productList[indexPath.row])
- productDetail.remove(at: indexPath.row)
- do {
- try managedContext.save()
- }
- catch let error as NSError {
- print("Error While Deleting Note: \(error.userInfo)")
- }
- tableView.deleteRows(at: [indexPath], with: .left)
- fetchCoreData()
- }
- }
- func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
- return true
- }
- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- let item = productDetail[indexPath.row]
- let vc = storyboard?.instantiateViewController(withIdentifier: "Cart") as! ProductDetailController
- vc.url = "\(url_productdetail)&product_id=\(String(describing: item.product_id!))"
- vc.hidesBottomBarWhenPushed = true
- self.navigationController?.pushViewController(vc, animated: false)
- }
- }
- extension CartController: UITableViewDataSource {
- public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell: CartCell = tableView.dequeueReusableCell(withIdentifier: "cartCell") as! CartCell
- // let cell: TestCell = tableView.dequeueReusableCell(withIdentifier: "TestCell") as! TestCell
- let item = productList[indexPath.row]
- count = productList.count
- cell.quantity = item.value(forKey: "quantity") as! Int
- if productList.count == productDetail.count {
- cell.cartTitleLabel.text = productDetail[indexPath.row].name
- cell.cartPriceLabel.text = productDetail[indexPath.row].price
- // let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.tappedMe))
- //
- // cell.cartImageView.addGestureRecognizer(tap)
- cell.cartQuantityNumberLabel.text = String(cell.quantity)
- let current_quantity = cell.quantity
- if productDetail[indexPath.row].image != nil {
- let url = URL(string: productDetail[indexPath.row].image!)
- let data = try? Data(contentsOf: url!)
- if data != nil {
- cell.imageButton.setImage(UIImage(data: data!), for: .normal)
- // cell.cartImageView.image = UIImage(data: data!)
- }
- else {
- cell.imageButton.setImage(#imageLiteral(resourceName: "default_image"), for: .normal)}
- // cell.cartImageView.image = #imageLiteral(resourceName: "default_image") }
- } else {
- cell.imageButton.setImage(#imageLiteral(resourceName: "default_image"), for: .normal)
- // cell.cartImageView.image = #imageLiteral(resourceName: "default_image")
- }
- DispatchQueue.main.async {
- if current_quantity != cell.quantity {
- self.updateQuantity(id: item.value(forKey: "product_id") as! String, quantity: cell.quantity, index: indexPath.row)
- self.fetchCoreData()
- }
- self.tableView.reloadData()
- }
- cell.imageButton.tag = indexPath.row
- cell.imageButton.addTarget(self, action: #selector(imageButtonClick(_:)), for: .touchUpInside)
- cell.deleteButton.tag = indexPath.row
- cell.deleteButton.addTarget(self, action: #selector(deleteButtonClick(_:)), for: .touchUpInside)
- }
- cell.backgroundColor = UIColor.clear
- return cell
- }
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return productList.count
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement