通过下拉来逐行刷新,需要在viewdidload上整个数组

时间:2019-04-05 12:43:40

标签: swift uitableview

当我通过下拉刷新控制器重新加载表格视图时,每次刷新都会使我一行一行。我希望所有行中的数据(视图已加载)并刷新。 表视图在视图控制器中,每次刷新/重新加载时我只有一行,但希望所有行都打开(视图确实已加载)和刷新。
 当我打开视图时,我得到了一行;当我刷新视图时,我又得到了一行,但是我想一次将所有行都放入(视图加载了)和refreshcontrol中。
    有三种方法(视图确实已加载)/视图将出现/刷新控件/我希望在viewdidload上获得cartData的整个值。


 public struct FavouriteCart {
    var p_name : String!
    var p_price : String!
    var p_id : String!
    var qty: String!

 public init(p_name: String ,  p_price: String , p_id : String, qty: String) {
        self.p_name = p_name
        self.p_price = p_price
        self.p_id = p_id
        self.qty = qty
    }

}

 public struct favSection {
    var favitems: [FavouriteCart]

    public init(favitems: [FavouriteCart]  ) {
        self.favitems = favitems
    }
}


    override func viewDidLoad() {
        super.viewDidLoad()
        //self.getFav()
       // self.reloadInputViews()

       // self.getFav()


        self.viewWillAppear(true)
          self.updateTableview()


        if btn2 != btn3 {
            lblPreorder.isHidden = true
            lblOrdermethod.isHidden = false
            print("BUTTONCLICKED")
             UserDefaults.standard.removeObject(forKey: "button1")
        } else if btn2 == btn3 {
            lblPreorder.isHidden = false
            lblOrdermethod.isHidden = true
            print("BUTTON-NOT-CLICKED")
            UserDefaults.standard.removeObject(forKey: "button1")
        }


//        self.view.layoutIfNeeded()
//        self.view.setNeedsDisplay()
//        self.getFav()
//        self.updateTableview()



        self.tableView.dataSource = self
        self.tableView.delegate = self
        print("111111111 ->  \(cartid)")

        self.view.addSubview(self.tableView)

        if #available(iOS 10.0, *) {
        tableView.refreshControl = refreshControl
        } else {
        tableView.addSubview(refreshControl)

        }
        refreshControl.addTarget(self, action: #selector(newCartViewController.refreshData), for: UIControlEvents.valueChanged)
//

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
      self.refreshData()
//        self.refreshData()
//        self.getFav()
      //  self.updateTableview()


    }


    @objc func refreshData() {

        self.getFav()
        self.getTotal1()
        self.updateTableview()

        self.refreshControl.endRefreshing()

    }

    func updateTableview() {

      DispatchQueue.main.async{

            self.tableView.reloadData()
        }
    }


    // Mark: getting all cart items:-->
    func getFav(){
        let request = getApi.displaycartGetWithRequestBuilder(restId: "17", cartId:cartid!)
        Alamofire.request(request.URLString, method: .get , parameters: nil, encoding: JSONEncoding.default)
            .responseJSON { response in
                print("123321/\(response)")
                let res = response
                print("101res/\(res)")

                let total =  self.cartData
                print("cartd1/\(total)")

    if let value = response.value as? [String: AnyObject] {
            if let success = value["error"] as? Bool {
            if success == false {
                print("2222/\(response)")
            if let response = value["cartdata"]  as? [String: AnyObject] {
                let cart = response["simple"] as! [[String: AnyObject]]
                var itemsdata: [FavouriteCart] = []
                                for (_ , value) in cart.enumerated() {

                                    let obj = value as! [String:AnyObject]
                                    let p_name = obj["p_name"] as! String
                                    let p_price = obj["p_price"] as! String
                                    let p_id = obj["p_id"] as! String
                                    let qty = obj["qty"] as! String

                                    var prid = p_id as! String
                                    print("stirng ID - > /\(p_id)")
                                    let item = FavouriteCart(p_name: p_name, p_price: p_price, p_id: p_id, qty: qty)

                                    itemsdata.append(item)



                                // self.cartData.append(favitems)

                                   print("hiiooooooooooooooooooooooo/\(itemsdata)")

                                }
                self.cartData.append(favSection(favitems: itemsdata))
                self.tableView.reloadData()
                            }
                        }
                    }
                    else
                    {
                        let myAlert = UIAlertController(title:"Alert",message:value["error_msg"] as? String,preferredStyle:UIAlertControllerStyle.alert)
                        let okAction = UIAlertAction(title:"OK",style:UIAlertActionStyle.default , handler: nil)
                        myAlert.addAction(okAction)
                    }
                }
        }
    }

    // Mark:--> Delete items from cart.
    // func delFav(p_id: String ,completionHandler: @escaping (Bool) -> Void) {
    func delFav(product_id: String, completionHandler: @escaping (Bool) -> Void){
        //var product1 = UserDefaults.standard.object(forKey: "p_id")
        //print("this is my \(product1)")
    let request = getApi.deleteproductcartGetWithRequestBuilder(restId: "17", cartId: cartid!, productId: product_id , freeDish: "none", type: "simple")
        Alamofire.request(request.URLString, method: .delete , parameters: nil, encoding: JSONEncoding.default)
            .responseJSON { response in
                print("del favvvvvvvvv\(response)")
                //print(response)
                if let value = response.value as? [String: AnyObject] {
                    if let success = value["error"] as? Bool {
                        if success == false {
                            let response = value["cartdata"] as? [String]
                            print("10001 - > /\(response)")

                            //self.tableView.reloadData()


                        } else
                        {
                            print("error message")
                        }
                    }

                }
                // completionHandler(true)
        }
    }


    func delterow(product_id: String) {
        self.delFav(product_id: product_id, completionHandler: {sucess in
            if sucess {
                print("DELETED_ITEM")
            }
        })
    }


}

extension newCartViewController: UITableViewDelegate , UITableViewDataSource{



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

//    func numberOfSections(in tableView: UITableView) -> Int {
//       return cartData.count
//    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

      // return sectionsData[section].items.count

      return cartData.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cartTablecell", for: indexPath) as! cartTableViewCell

    let item: FavouriteCart = cartData[indexPath.section].favitems[indexPath.row]

     cell.btnsub1.tag = indexPath.row
     cell.btnadd1.tag = indexPath.row


        cell.lblItemName.text = item.p_name
        cell.productPrice.text = item.p_price
        cell.lblprice.text = item.p_price



        return cell


    }


    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool{
        return true

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


    if (editingStyle ==  .delete) {
        let item: FavouriteCart = cartData[indexPath.section].favitems[indexPath.row]
        self.delterow(product_id: item.p_id)

        self.tableView.reloadData()

       }

    }


}

1 个答案:

答案 0 :(得分:0)

used completion handler in the api call and reloaded the data in the  api call :-----


  override func viewDidLoad() {
        super.viewDidLoad()

       // self.getFav()
       //self.viewWillAppear(true)
      // refreshControl.addTarget(self, action: #selector(viewDidAppear(_:)), for: UIControlEvents.valueChanged)
        refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refreshControl.addTarget(self, action: #selector(newCartViewController.refreshData), for: UIControlEvents.valueChanged)
        tableView.addSubview(refreshControl)


        if btn2 != btn3 {
            lblPreorder.isHidden = true
            lblOrdermethod.isHidden = false
            print("BUTTONCLICKED")
             UserDefaults.standard.removeObject(forKey: "button1")
        } else if btn2 == btn3 {
            lblPreorder.isHidden = false
            lblOrdermethod.isHidden = true
            print("BUTTON-NOT-CLICKED")
            UserDefaults.standard.removeObject(forKey: "button1")
        }


//        self.view.layoutIfNeeded()
//        self.view.setNeedsDisplay()
//        self.getFav()
//        self.updateTableview()



        self.tableView.dataSource = self
        self.tableView.delegate = self
        print("111111111 ->  \(cartid)")

        self.view.addSubview(self.tableView)

        if #available(iOS 10.0, *) {
        tableView.refreshControl = refreshControl
        } else {
        tableView.addSubview(refreshControl)

        }



    }

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

        self.getFav()

    }


       @objc func refreshData() {

        self.getFav()
        self.getTotal1()
        DispatchQueue.main.async {
        self.refreshControl.endRefreshing()
        }
         }


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



    func getFav() {
        getFav(completionHandler: { success in
            if success {
                DispatchQueue.main.async{
                    self.tableView.reloadData()
                }
            }
        })
    }

    //TOTAL API CALL:
    func getTotal1() {
        let request = getApi.getamountcartGetWithRequestBuilder(restId: "17", cartId: (cartid as? String)!)
        Alamofire.request(request.URLString, method: .get , parameters: nil, encoding: JSONEncoding.default)
            .responseJSON { response in
                print("123321#######/\(response)")
                let res = response
                print("101res/\(res)")


        if let value = response.value as? [String: AnyObject] {
        if let success = value["error"] as? Bool {
            if success == false {
            var  grandtotal = value["total"] as Any
                var gtotal = grandtotal

                print("^^^^^/\(gtotal)")
            print("@@@@/\(grandtotal)")

       UserDefaults.standard.set(10, forKey: "gtotal")


                        }
                    }
                }
          }
    }
//
    // Mark: getting all cart items:-->
    func getFav(completionHandler: @escaping (Bool) -> Void){
        let request = getApi.displaycartGetWithRequestBuilder(restId: "17", cartId:cartid!)
        Alamofire.request(request.URLString, method: .get , parameters: nil, encoding: JSONEncoding.default)
            .responseJSON { response in
                print("123321/\(response)")
                let res = response
                print("101res/\(res)")

                let total =  self.cartData
                print("cartd1/\(total)")

    if let value = response.value as? [String: AnyObject] {
            if let success = value["error"] as? Bool {
            if success == false {
                print("2222/\(response)")
            if let response = value["cartdata"]  as? [String: AnyObject] {
                let cart = response["simple"] as! [[String: AnyObject]]
//                let total = value["total"] as! [String: Any]
//                print("1231231231234/\(total)")
                                //let userdata: [Favourites] = []
               //
                var cartData: [FavouriteCart] = []
                                for (_ , value) in cart.enumerated() {

                                    let obj = value as! [String:AnyObject]
                                    let p_name = obj["p_name"] as! String
                                    let p_price = obj["p_price"] as! String
                                    let p_id = obj["p_id"] as! String
                                    let qty = obj["qty"] as! String
                                  //  UserDefaults.standard.set(qty, forKey: "qty")
                                    var prid = p_id as! String
                                    print("stirng ID - > /\(p_id)")
                                    let item = FavouriteCart(p_name: p_name, p_price: p_price, p_id: p_id, qty: qty)

                                    cartData.append(item)
                                    DispatchQueue.main.async{
                                        print("RELOADED-----ON-----API")
                                        self.cartData.append(favSection(favitems: cartData))
                                        self.tableView.reloadData()
                                    }
//                                   self.tableView.reloadData()

                                // self.cartData.append(favitems)


                                    //QTY::::::-------
//                                    let quant = QtyCart(qty: qty)
//                                    self.qtyData.append(quant)
//

                                   //print("hiiooooooooooooooooooooooo/\(itemsdata)")

                                }


                            }
                print("COMPLETION-------------HANDLER")
                completionHandler(true)
                        }

                    }
                    else
                    {
                        let myAlert = UIAlertController(title:"Alert",message:value["error_msg"] as? String,preferredStyle:UIAlertControllerStyle.alert)
                        let okAction = UIAlertAction(title:"OK",style:UIAlertActionStyle.default , handler: nil)
                        myAlert.addAction(okAction)
                    }
                }
        }
    }