通过下拉刷新逐一获取行,想要在 viewdidload 上的整个数组

Posted

技术标签:

【中文标题】通过下拉刷新逐一获取行,想要在 viewdidload 上的整个数组【英文标题】:Getting rows one by one on refreshing by pulling down ,wanted whole array on viewdidload 【发布时间】:2019-04-05 12:43:39 【问题描述】:

当我通过下拉刷新控制器重新加载 tableview 时,它会在每次刷新时让我一个接一个地获取行。我想要(视图确实加载)和刷新中的所有行数据。 表视图在视图控制器中,我在每次刷新/重新加载时获得一行,但希望所有行都打开(视图确实加载)并刷新。 当我打开视图时,我得到了一行,当我刷新视图时,我又得到了一行,但希望在(视图确实加载)和刷新控制中一次性拥有所有行。 共有三种方法(视图确实加载)/视图将出现/刷新控件/我想要 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()

       

    



【问题讨论】:

从 viewDidLoad 中取消注释 self.getFav() 这是大量代码(以及空行、打印行和注释行),您能否通过使其更紧凑并删除与您的问题无关的任何内容来清除它? 是他们对我的代码的任何解决方案吗? 【参考方案1】:
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)
                    
                
        
    

【讨论】:

以上是关于通过下拉刷新逐一获取行,想要在 viewdidload 上的整个数组的主要内容,如果未能解决你的问题,请参考以下文章

android pulltorefresh是怎么触发下拉刷新的

通过Hack方式实现SDC中Stage配置联动刷新

小程序 (下拉刷新,上拉加载)

Jetpack Compose : 一学就会的自定义下拉刷新&加载更多

Jetpack Compose : 一学就会的自定义下拉刷新&加载更多

React组建实现新闻下拉刷新加载