Swift tableView Pagination

后端 未结 14 1404
长情又很酷
长情又很酷 2020-11-28 20:00

I have success working tableview with json parsing codes.But may have 1000 more item so need pagination when scrolling bottom side. I dont know how can i do this my codes un

14条回答
  •  清歌不尽
    2020-11-28 20:50

    API handler is api handler for network call that just do POST and GET calls. getNotifications is basically just a post call with params( offset and pageSize ) and in response there is list. Main logic is changing offset depending on cell in willDisplay collectionView delegate. Comment if you having any question , happy to help.

    var isFetching: Bool = false
    var offset = 0
    var totalListOnServerCount = 20 // it must be returned from server
    var pageSize = 10 // get 10 objects for instance
    // MARK: - API Handler
    private func fetchNotifications(){
        // return from function if already fetching list
        guard !isFetching else {return}
            if offset == 0{
                // empty list for first call i.e offset = 0
                self.anyList.removeAll()
                self.collectionView.reloadData()
            }
            isFetching = true
            // API call to fetch notifications with given offset or page number depends on server logic just simple POST Call
            APIHandler.shared.getNotifications(offset: offset) {[weak self] (response, error) in
                if let response = response {
                    self?.isFetching = false
                    if self?.offset == 0{
                        // fetch response from server for first fetch
                        self?.notificationsResponse = response
                        if self?.refreshControl.isRefreshing ?? false {
                            self?.refreshControl.endRefreshing()
                        }
                    }else{
                        // append if already exist ( pagination )
                        self?.notificationsResponse?.notifications.append(contentsOf: response.notifications)
                    }
                    self?.collectionView.reloadData()
    
                }
    
            }
    }
    
    
    // MARK: - Collection View Delegate
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    
        guard let anyList = responseFromServer else { return }
        // check if scroll reach last index available and keep fetching till our model list has all entries from server
        if indexPath.item == anyList.count - 1 && anyList.count  < totalListOnServerCount{
    
            offset += pageSize
            fetchNotifications()
    
        }
    }
    

提交回复
热议问题