Swift 4:使用数组中的数据进行分页以在用户滚动时进行API调用

时间:2019-03-22 06:58:48

标签: ios arrays swift api uitableview

背景

在我的应用程序中,我存储了一堆对象ID。我使用这些ID进行批处理API调用。 API将每个调用限制为10个ID号。此数据呈现在UITableView上。用户可以添加和删除对象,这可以从数据库中添加或删除对象ID。

我正在使用Firestore数据库存储对象ID。

当前实施

这是我到目前为止所执行的操作,但是在添加和删除对象时会导致应用程序崩溃。我还无法弄清楚如何正确处理这些案件,以及这是否是执行此类操作的正确模式。

  1. 获取用于进行API调用的对象ID
var objectIds: [String] = []
var chunkedObjectIds: [[String]] = []
var objects: [Array] = []
var offset: Int = 0

override func viewDidLoad() {
    super.viewDidload()

    getObjectIds()

 }

func getObjectIds() {
    // get objects IDs and store then in objectIds from the Firestore database
    // setup the .addSnapshotLister so the query is triggered whenever there is a change in the data on Firestore for the collection

    return chunkedObjectIds

    // when finished, get the first 10 objects from the 3rd party API

    fetchObjects()

}
  1. 获取对象Ids数组,将其拆分为数组数组(每10个数组),并对前10个进行API调用
func fetchObjects() {

     // split objectIds array in array of arrays, in lots of 10
     // chunkedObjectIds is set here

     // request the objects for the first 10 ID numbers

    Alamofire.request(… parameter with first 10 object ids …) (objects) in {

        // save objects

        // increment the offset
        offset += 1
    }

}
  1. 在UITableView单元格上呈现数据

  2. 使用以下方法从第三方API加载更多数据:

 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        let lastRow = objects.count 

        var parameters = [String: Any]()

        if indexPath.row == lastRow {
            if !(offset == self.chunkedObjectIds.count) {

                // process the next batch from the array
                parameters["id-numbers"] = self.chunkedObjectIds[offset].map{String($0)}.joined(separator: ",")

                Alamofire.request(… paramaters: parameters) { (objects) in
                    for item in 0..<objects.count {
                        let indexPath = IndexPath(row: item + self.objects.count, section: 0)
                        self.paths.append(indexPath)
                    }
                    self.objects.append(contentsOf: objects)
                    self.tableView.beginUpdates()
                    self.tableView.insertRows(at: self.paths, with: .automatic)
                    self.tableView.endUpdates()
                    self.paths.removeAll()
                    self.offset += 1
                }
            }
        }
    }
  1. 添加或删除对象:

    • 从Firestore数据库中添加或删除对象ID
    • 清除了objectIds,chunkedObjectIds,offset和对象
    • 侦听器触发读取数据,然后重复该过程

问题与问题

这非常适合加载初始数据。但是复制会在添加时发生(有时会崩溃)。删除应用程序时,由于超出范围的异常会导致崩溃。

这是一开始使用的正确模式吗?如果是这样,那么我在第一次加载后要处理的情况,尤其是新对象ID的添加和删除,我缺少什么。

编辑

我已根据评论中的反馈更改了实现。所以现在,过程是这样的:

  1. 设置侦听器以从Firestore获取数据
  2. 在Firestore中遍历对象ID,当计数器小于10或到达object.count时-现在保存下一个偏移量,并在下次触发此方法时,使用相同的下一个偏移量启动循环有条件的时候
  3. 从第三方API获取对象
  4. 我一直使用willDisplay cell方法来触发更多数据加载-它似乎比scrollDidEnd方法更可靠。

所以现在该应用程序不再崩溃。 Firestore侦听器存在一些问题,但我将其作为一个单独的问题发布。

0 个答案:

没有答案