完成数据加载后,不会删除swift activityIndi​​cater

时间:2017-08-31 03:07:42

标签: json swift tableview infinite-scroll

我在tableView中有一个无限滚动,比如facebook,它运行得很好,但问题是当完成数据加载时,activityIndi​​cator不会隐藏。

NetworkRequestAPI请求

import Foundation

class NetworkRequestAPI {        

    static func getPropductListByCategory(productId : Int, pageNo : Int , completion: @escaping ([Product]? , Error?) -> ()){

        let url = URL(string: Configuration.BASE_URL+"/product-by/type?product_type_id="+String(productId)+"&page="+String(pageNo))
        var categoryObject = [Product]()
        URLSession.shared.dataTask(with:url!) { (urlContent, response, error) in

            if error != nil {

            }
            else {
                do {
                    let json = try JSONSerialization.jsonObject(with: urlContent!) as! [String:Any]

                    let products = json["products"] as? [String: Any]
                    //   productCount = (json["product_count"] as? Int)!

                    let items = products?["data"] as? [[String:Any]]
                    items?.forEach { item in
                        let oProduct = Product()
                        oProduct.product_id = item["product_id"] as? Int
                        oProduct.product_name = item["product_name"] as? String
                        oProduct.product_image = item["product_image"] as? String
                        let ratingItem = item["rating_info"] as? [String: AnyObject]

                        let rating = RatingInfo()
                        rating.final_rating = ratingItem?["final_rating"] as? String
                        oProduct.rating_info = rating
                        categoryObject.append(oProduct)
                    }
                    completion(categoryObject, nil)

                } catch let error as NSError {

                    print(error)
                    completion(nil, error)
                }
            }


            }.resume()
    }


}

ListTableView类

class ListTableView: UITableViewController {
    var isInitUILoad = true
    var arrProduct = [[Product]]()
    var product_id:Int = 0
    var pageNo = 1

    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUILoad()
    }

    func initUILoad(){
        ActivityIndicator.customActivityIndicatory(self.view, startAnimate: true)
        NetworkRequestAPI.getPropductListByCategory(productId: product_id, pageNo: pageNo) { (products, error) in

            DispatchQueue.main.async(execute: {
                if products != nil {
                    self.pageNo += 1
                    self.arrProduct.append(products!)
                    print(self.arrProduct.count)
                }else{
                    print(error.debugDescription)
                }

                ActivityIndicator.customActivityIndicatory(self.view, startAnimate: false)
                self.tableView?.reloadData()
                self.isInitUILoad = false
            })
        }
    }

    func loadMore(complition:@escaping (Bool) -> ()) {
        NetworkRequestAPI.getPropductListByCategory(productId: product_id, pageNo: pageNo) { (products, error) in
            DispatchQueue.main.async(execute: {
                if error != nil{
                    print(error.debugDescription)
                }
                if products != nil && products?.count ?? 0 > 0{
                    self.pageNo += 1
                    self.arrProduct.append(products!)                      self.tableView?.insertSections([self.arrProduct.count - 1], with: .fade)

                }else{
                    print("no product left")
                }
                complition(true)
            })
        }
    }


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

        let cell = tableView.dequeueReusableCell(withIdentifier: categoryCellid, for: indexPath) as! ListTableCell
        var categoryObject = arrProduct[indexPath.section]
        cell.product = categoryObject[indexPath.item]
        return cell
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 115.0
    }
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
           let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: footerCellid) as! HeadFooterCell
        if !isInitUILoad {
            tableView.tableFooterView?.isHidden = true
            loadMore(complition: { (isDone) in
                footerView.activityIndicatorView.stopAnimating()
            })
        }
        return footerView
    }


    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let lastSectionIndex = tableView.numberOfSections - 1
        let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1
        if indexPath.section ==  lastSectionIndex && indexPath.row == lastRowIndex {
            // print("this is the last cell")
            let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
            spinner.startAnimating()
            spinner.backgroundColor = .green
            spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: tableView.bounds.width, height: CGFloat(44))
            self.tableView.tableFooterView = spinner
            self.tableView.tableFooterView?.isHidden = false
        }

    }

HeadFooterCell

class HeadFooterCell: UITableViewHeaderFooterView {
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        setupViews()
    }

    var activityIndicatorView : UIActivityIndicatorView = {
        var activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        activityIndicatorView.backgroundColor = UIColor.cyan
        return activityIndicatorView
    }()
    func setupViews() {
        addSubview(activityIndicatorView)
        addConstraintsWithFormat("H:|[v0]|", views: activityIndicatorView)
        addConstraintsWithFormat("V:|[v0(50)]|", views: activityIndicatorView)
    }
   required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

1 个答案:

答案 0 :(得分:0)

你需要在主线程中停止它:

DispatchQueue.main.async {
    footerView.activityIndicatorView.stopAnimating()
}

另外,将hidesWhenStopped设置为true:

footerView.activityIndicatorView.hidesWhenStopped = true