UITableView load more when scrolling to bottom like Facebook application

后端 未结 18 2117

I am developing an application that uses SQLite. I want to show a list of users (UITableView) using a paginating mechanism. Could any one please tell me how to load more dat

18条回答
  •  [愿得一人]
    2020-11-27 09:43

    for loading from an API, It works for me, Xcode10 , swift 4.2 :

    1- create New Swift file and do like this:

    //
    //  apiTVCController.swift
    //  ApiTestingTableView
    //
    //  Created by Hooma7n on 4/7/19.
    //  Copyright © 2019 Hooma7n. All rights reserved.
    //
    
    import Foundation
    import Alamofire
    
    class apiget {
    
        var tableData : [Datum] = []
        var loadin : [Datum] = []
        var testfortotal : Int?
    
    
        func getfromapi(completionHandler : ((_ isSucess : Bool) -> Void)?) {
            let url = "https://reqres.in/api/users?page=1"
            Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
                .responseJSON(completionHandler : { response in
                    switch response.result {
                    case .success(let data):
                        guard let jsonData = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted) else {return}
                        let decoder = JSONDecoder()
                        guard let result = try? decoder.decode(Welcome.self, from: jsonData) else {return}
                        self.tableData = result.data ?? []
                        self.testfortotal = result.total ?? 0
                        completionHandler?(true)
    
                    //                    print(result)
                    case .failure(let error):
                        print(error)
                    }
                })
        }
    
        var pagecounter : Int = 2
    
    
        func loadmore(completionHandler : ((_ isSucess : Bool) -> Void)?){
    
            let url = "https://reqres.in/api/users?page=\(pagecounter)"
            Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
                .responseJSON(completionHandler : { response in
                    switch response.result {
                    case .success(let data):
                        guard let jsonData = try? JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted) else {return}
                        let decoder = JSONDecoder()
                        guard let myresult = try? decoder.decode(Welcome.self, from: jsonData) else {return}
                        self.loadin = myresult.data ?? []
                        self.tableData.append(contentsOf: myresult.data ?? [])
                        completionHandler?(true)
                        print(self.pagecounter)
                        self.pagecounter += 1
    
                    //                    print(myresult)
                    case .failure(let error):
                        print(error)
                    }
                })
    
        }
    
    }
    
    extension apiget {
    
        struct Welcome: Codable {
            let page, perPage, total, totalPages: Int?
            var data: [Datum]?
    
            enum CodingKeys: String, CodingKey {
                case page
                case perPage = "per_page"
                case total
                case totalPages = "total_pages"
                case data
            }
        }
    
        struct Datum: Codable {
            let id: Int?
            let firstName, lastName: String?
            let avatar: String?
    
            enum CodingKeys: String, CodingKey {
                case id
                case firstName = "first_name"
                case lastName = "last_name"
                case avatar
            }
        }
    
    
    }
    

    2- in Your ViewController file (tableView Controller) :

    //
    //  apiTVC.swift
    //  ApiTestingTableView
    //
    //  Created by Hooma7n on 4/7/19.
    //  Copyright © 2019 Hooma7n. All rights reserved.
    //
    
    import UIKit
    import Alamofire
    
    class apiTVC: UITableViewController {
    
        var datamodel = apiget()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            datamodel.getfromapi(completionHandler: {finish in
                if finish {self.tableView.reloadData()
                }
    
            })
    
        }
    
    
        override func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return datamodel.tableData.count
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! apiTableViewCell
            cell.firstNameLabel.text = datamodel.tableData[indexPath.row].firstName
            cell.lastNameLabel.text = datamodel.tableData[indexPath.row].lastName
            cell.dateLabel.text = "\(datamodel.tableData[indexPath.row].id ?? 0)"
            cell.profileImageView.loadImage(fromURL: datamodel.tableData[indexPath.row].avatar ?? "")
    
            return cell
    
        }
    
        override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            let lastElement = datamodel.tableData.count - 1
            let total = datamodel.testfortotal ?? 12
            if indexPath.row == lastElement && datamodel.tableData.count < total{
    
                datamodel.loadmore(completionHandler: {finish in
                    if finish {
    
                        self.tableView.reloadData()
    
                    }})
            }
        }
    }
    

    if using tableView in Your viewController set delegate,datasource self in viewDidLoad.

提交回复
热议问题