拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何增加URL中的页面计数以加载更多资料并在底部显示指示器?

如何增加URL中的页面计数以加载更多资料并在底部显示指示器?

白鹭 - 2022-01-25 2164 0 0

我创建了一个 web 服务的演示,在此我想增加页数并从 api 加载更多资料,并在活动指示器重绘 后添加表格视图。我发现很多教程,但没有发现有用......它们都是高级的,我是初学者,所以我没有正确。任何人都可以告诉如何做到这一点。

这是我的演示详细信息...

这是 URL 的页数

 "info": {
    "count": 826,
    "pages": 42,
    "next": "https://rickandmortyapi.com/api/character/?page=3",
    "prev": "https://rickandmortyapi.com/api/character/?page=1"
  },

我的 json 模型

import UIKit
import Foundation

// MARK: - JsonModel
struct JSONModel:Decodable {
let info: Info
let results: [Result]
}

// MARK: - Info
 struct Info : Decodable {
let count, pages: Int
let next: String
let prev: NSNull
 }

  // MARK: - Result
 struct Result : Decodable {
let id: Int
let name: String
let status: Status
let species: Species
let type: String
let gender: Gender
let origin, location: Location
let image: String
let episode: [String]
let url: String
let created: String
 }

enum Gender {
case female
case male
case unknown
 }

// MARK: - Location
struct Location {
let name: String
let url: String
 }

enum Species {
case alien
case human
}

enum Status {
case alive
case dead
case unknown
 }

这是我的视图控制器类

import UIKit
import Kingfisher

class ViewController: UIViewController,UISearchBarDelegate{



@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!

var results = [Results]()
var filteredData = [Results]()
var batchSize = 42
var fromIndex = 0

override func viewDidLoad() {
    super.viewDidLoad()
    searchBar.delegate = self
    tableView.delegate = self
    tableView.dataSource = self
    apiCalling()
    filteredData = results
    
}

override func viewWillAppear(_ animated: Bool) {
    filteredData = results
    self.tableView.reloadData()
}


func apiCalling(){
    
    
    guard let url = URL(string: "https://rickandmortyapi.com/api/character/") else { return }
    URLSession.shared.dataTask(with: url) {[weak self]data, response, error in
        
        
        if error != nil{
            print("error While Fetching Data")
        }
        
        guard let data = data else {
            return
        }
        do {
            let resultData = try JSONDecoder().decode(JsonModel.self, from: data)
            self?.results = resultData.results!
            self?.filteredData = self!.results
            DispatchQueue.main.async {
                self?.tableView.reloadData()
            }
          
        } catch  {
            print(error.localizedDescription)
        }
    }.resume()

}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
   
    let searchText = searchBar.text!
    guard !searchText.isEmpty else {
        filteredData = results
        tableView.reloadData()
        return
    }
    filteredData = results.filter({ $0.name!.lowercased().contains(searchText.lowercased() ) })
    tableView.reloadData()


    }





func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        self.searchBar.showsCancelButton = true
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.showsCancelButton = false
        searchBar.text = ""
        searchBar.resignFirstResponder()
        filteredData.removeAll()
        self.tableView.reloadData()
   }


 }

这是我的 Tableview 扩展

extension ViewController : UITableViewDelegate, UITableViewDataSource  {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredData.count 
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! UserTableViewCell
    let row = filteredData[indexPath.row]
    let imageUrl = URL(string: row.image!)
    cell.userImage.kf.setImage(with: imageUrl)
    cell.lblGender.text = "Gender:- \(row.gender ?? "no value")"
    cell.lblID.text = "ID:- \(row.id ?? 0)"
    cell.lblName.text = "Name: \(row.name!)"
    cell.lblSpecies.text = "Species:- \(row.species ?? "No Speies")"
    return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
    
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 250
}
}

uj5u.com热心网友回复:

你需要保存页面信息。

self?.info = resultData.info!

加载更多资料时呼叫“loadpage”

override func viewDidLoad() {
    super.viewDidLoad()
    searchBar.delegate = self
    tableView.delegate = self
    tableView.dataSource = self
    filteredData = []
    result = []
    apiCalling(apiurl:"https://rickandmortyapi.com/api/character/")
}

func apiCalling(apiurl:String){
    
    
    guard let url = URL(string: apiurl) else { return }
    URLSession.shared.dataTask(with: url) {[weak self]data, response, error in
        
        
        if error != nil{
            print("error While Fetching Data")
        }
        
        guard let data = data else {
            return
        }
        do {
            let resultData = try JSONDecoder().decode(JsonModel.self, from: data)
            self?.results.append(resultData.results!)
            self?.info = resultData.info!
            filterWord()
          
        } catch  {
            print(error.localizedDescription)
        }
    }.resume()

}

func filterWord(){
    let searchText = searchBar.text!
    guard !searchText.isEmpty else {
        filteredData = results
        tableView.reloadData()
        return
    }
    filteredData = results.filter({ $0.name!.lowercased().contains(searchText.lowercased() ) })
    tableView.reloadData()
}

func loadPage(){
    guard let page = self?.info.next,!page.isEmpty else{
        return
    }
    apiCalling(apiurl:page)
}

在这样的指标简单示例下

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    guard let page = self?.info.next,!page.isEmpty else{
        return nil
    }
    //press to call loadPage
    let loading = UIButton.init()
    let view = UIView.init()
    view.addSubview(loading)
    return view
}

uj5u.com热心网友回复:

我在这里给出我自己的问题答案...

我已经创建了另外 3 个变量

 var curentIndex : Int = 0
// I'm Putting Default Limit Here...
var numberArray = Array(1...42)
var fetchingMore = false

API 呼叫

func apiCalling(){
    guard !fetchingMore else  {
        print("Didn't call Get Data")
        return
    }
    
    fetchingMore = true
    guard let url = URL( string: "\(baseUrl)?page=\(numberArray[curentIndex])") ?? URL(string: "" ) else {
        fetchingMore = false
        return
    }
    
    curentIndex  = 1
    URLSession.shared.dataTask(with: url) {[weak self]data, response, error in
        if error != nil{
            print("error While Fetching Data")
        }
        guard let data = data else {
            return
        }
        do {
            let resultData = try JSONDecoder().decode(JsonModel.self, from: data)
            self?.results  = resultData.results!
            self?.filteredData = self!.results
            DispatchQueue.main.async {
                self?.tableView.reloadData()
            }
        } catch  {
            print(error.localizedDescription)
        }
        self?.fetchingMore = false
    }.resume()
}

**这是我的 CellForRowMethod **

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! UserTableViewCell
    let row = filteredData[indexPath.row]
    if indexPath.row == filteredData.count - 1 && curentIndex <= row.id ?? 0 {
        apiCalling()
    }
    let imageUrl = URL(string: row.image!)
    cell.userImage.kf.setImage(with: imageUrl)
    cell.lblGender.text = "Gender:- \(row.gender ?? "no value")"
    cell.lblID.text = "ID:- \(row.id ?? 0)"
    cell.lblName.text = "Name: \(row.name!)"
    cell.lblSpecies.text = "Species:- \(row.species ?? "No Speies")"
    return cell
}
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *