pour le chargement depuis une API, ça marche pour moi, Xcode 10 , swift 4.2 :
1- Créez un nouveau fichier Swift et faites comme ceci:
//
// 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- dans votre fichier ViewController (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()
}})
}
}
}
si vous utilisez tableView dans votre jeu viewController délégué , source de données auto à viewDidLoad.