由于实施了分页

时间:2017-10-09 05:34:04

标签: ios uitableview swift3 pagination

这里我已经为表视图实现了分页,并且使用模型类加载了项目,但是这里加载的项目正在替换为新项目,并且一次只显示10个项目我是第一次实现它可以任何人帮助我该如何解决这个问题?

func listCategoryDownloadJsonWithURL(listUrl: String) {
        let url = URL(string: listUrl)!
        print(listUrl)
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil { print(error!); return }
            do {
                if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
                    self.listClassModel = ModelClass(dict: jsonObj as [String : AnyObject])
                    DispatchQueue.main.async {
                        guard let obj = self.listClassModel else { return }
                        let itemsCount = obj.items.count
                        print(itemsCount)
                        for i in 0..<itemsCount {
                            let customAttribute = obj.items[i].customAttribute
                            for j in 0..<customAttribute.count {
                                if customAttribute[j].attributeCode == "image" {
                                    let baseUrl = "http://192.168.1.11/magento2/pub/media/catalog/product"
                                    self.listCategoryImageArray.append(baseUrl + customAttribute[j].value)
                                    print(self.listCategoryImageArray)
                                }
                            }
                        }
                        self.activityIndicator.stopAnimating()
                        self.activityIndicator.hidesWhenStopped = true
                        self.collectionView.delegate = self
                        self.collectionView.dataSource = self
                        self.collectionView.reloadData()
                        self.collectionView.isHidden = false
                        self.tableView.reloadData()
                    }
                }
            } catch {
                print(error)
            }
        }
        task.resume()
    }
func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let obj = listClassModel?.items
        return obj?.count ?? 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "productsCell", for: indexPath) as! productsCell
        let arr = listClassModel?.items[indexPath.row]
        let images = listCategoryImageArray[indexPath.row]
        let urls = NSURL(string: images)
        self.tableView.isHidden = false
        cell.productImage.hnk_setImageFromURL(urls! as URL)
        cell.productName.lineBreakMode = NSLineBreakMode.byWordWrapping
        cell.productName.numberOfLines = 2
        cell.productName.text = arr?.name
        cell.productPrice.text = "$\( (arr?.price)!).00"
        cell.buynowButton .addTarget(self, action: #selector(buyNowButton(_:)), for:UIControlEvents.touchUpInside)
        cell.cartButton .addTarget(self, action: #selector(cartButton(_:)), for:UIControlEvents.touchUpInside)
        return cell
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let obj = listClassModel?.items
        let lastElement = (obj?.count)! - 1
        if !loadingData && indexPath.row == lastElement {
            loadingData = true
            loadMoreData()
        }
    }

这是将新数据导入表视图的代码

    func loadMoreData() {
        DispatchQueue.global(qos: .background).async {
            guard let obj = self.listClassModel else { return }
            let  totalItems = obj.totalCount
            let numberOfItems = obj.searchCriteria.pageSize
            var count = 0
            let float = Float(totalItems)/Float(numberOfItems)
            print(float.cleanValue)
            let totalPages = Int(ceil(float))
            if totalPages != count {
                    let batchSize = 10
                    self.index += 1
                    count += 1
                    print(self.index)
                    let sortOrder = "ASC"
                    let conditionType = "eq"
                    let sortField = "name"
                    let listUrlWithParameters  = "http://192.168.1.11/magento2/rest/V1/products?searchCriteria[filterGroups][0][filters][0][field]=category_id&searchCriteria[filterGroups][0][filters][0][value]=17&searchCriteria[filterGroups][0][filters][0][conditionType]=\(conditionType)&searchCriteria[sortOrders][0][field]=\(sortField)&searchCriteria[sortOrders][0][direction]=\(sortOrder)&searchCriteria[pageSize]=\(batchSize)&searchCriteria[currentPage]=\(self.index)"
                    self.listCategoryDownloadJsonWithURL(listUrl: listUrlWithParameters)
            }
            DispatchQueue.main.async {
            // this runs on the main queue
            self.loadingData = false
            }

        }
    }
struct ModelClass {
    var items : [List]
    var totalCount : Int
    var searchCriteria : SearchCriteria

    init(dict:[String:AnyObject]) {
        totalCount = dict["total_count"] as! Int

        let searchDict = dict["search_criteria"] as? [String:AnyObject]
        searchCriteria = SearchCriteria(dict: searchDict!)

        let arr = dict["items"] as? [[String:AnyObject]]
        var listArr = [List]()
        for obj in arr! {
            listArr.append(List(dict: obj))
        }
        items = listArr
    }
}

struct List {

    let name : String
    let sku : Any
    let id : Int
    let attributeSetId : Int
    let price : Int
    let status : Int
    let visibility : Int
    let typeId: String
    let createdAt : Any
    let updatedAt : Any
    var customAttribute = [ListAttribute]()

    init(dict : [String:Any]) {
        if let customAttribute = dict["custom_attributes"] as? [[String: AnyObject]] {
            var result = [ListAttribute]()
            for obj in customAttribute {
                result.append(ListAttribute(json: obj)!)
            }
            self.customAttribute = result
        } else {
            self.customAttribute = [ListAttribute]()
        }
        self.name = (dict["name"] as? String)!
        self.sku = dict["sku"]!
        self.id = (dict["id"] as? Int)!
        self.attributeSetId = (dict["attribute_set_id"] as? Int)!
        self.price = (dict["price"] as? Int)!
        self.status = (dict["status"] as? Int)!
        self.visibility = (dict["visibility"] as? Int)!
        self.typeId = (dict["type_id"] as? String)!
        self.createdAt = dict["created_at"]!
        self.updatedAt = dict["updated_at"]!
    }
}
struct ListAttribute {

    let attributeCode : String
    let value : String

    init?(json : [String:AnyObject]) {

        self.attributeCode = (json["attribute_code"])! as! String
        self.value = (json["value"])! as! String

    }
}
struct SearchCriteria {
    var filterGroup : [FilterGroup]
    var sortGroup : [SortGroup]
    var pageSize : Int
    var pageNumber : Int

    init(dict:[String:AnyObject]) {
        if let arr = dict["filter_groups"] as? [[String: AnyObject]]{
            var filterArr = [FilterGroup]()
            for obj in arr {
                filterArr.append(FilterGroup(dict: obj))
            }
            self.filterGroup = filterArr
        } else {
            self.filterGroup = [FilterGroup]()
        }
        if let arr = dict["sort_orders"] as? [[String: AnyObject]]{
            var filterArr = [SortGroup]()
            for obj in arr {
                filterArr.append(SortGroup(dict: obj))
            }
            self.sortGroup = filterArr
        } else {
            self.sortGroup = [SortGroup]()
        }
        self.pageSize = dict["page_size"] as! Int
        self.pageNumber = dict["current_page"] as! Int
    }
}

0 个答案:

没有答案