ios - 为什么我的 "pull down to load data"卡在第 2 页而没有加载更多数据

标签 ios uitableview swift uiscrollview infinite-scroll

是否有关于通过将 json 中的新数据附加到旧数据来重新加载新数据的理论?我在解决该情况时遇到问题。我使用了 this infinite uitableview从我的 api json 字符串重新加载更多数据。我的 Api 根据页码返回结果。

我的 json header 包括“totalCount”、“currentPage”和“toPage”,如下面的代码中所述。“totalCount”表示我将获得的总结果。但是,它每页给出 15 个结果.所以,如果“totalCount”是 636。我必须翻 43 页(toPage)。

这是我的代码。

ViewController.swift

import UIKit

class ViewController: UITableViewController,AuctionAPIProtocol{

var currentPage = 1
var currentCount = 0
var toPage = 0

var totalCount = 0

var api : AuctionAPI?
let cellId = "cell"

@IBOutlet var tableViewFooter:MyFooter! //Table Footer which was activity indicator

var items:[AuctionModel] = []//An empty array where items gonna store

var newItems:[AuctionModel] = []

var loading = false // Loading State for activity indicator


override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellId)

    self.tableViewFooter.hidden = true
    api = AuctionAPI(delegate: self)
    api!.searchAuctionLatestFor("null",lotId: "1",page: "1")
}

//TableView Delegate and Datasource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as UITableViewCell

    let item = items[indexPath.row]

    cell.textLabel?.text = item.vendorName.capitalizedString+"  "+item.modelName.capitalizedString+" "+item.year

    return cell
}


override func scrollViewDidScroll(scrollView: UIScrollView) {
    // UITableView only moves in one direction, y axis
    let currentOffset = scrollView.contentOffset.y
    let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
    // Change 10.0 to adjust the distance from bottom
        if (maximumOffset - currentOffset) <= 40.0 {
            loadSegment(currentPage, count: items.count)
        }
}


func loadSegment(currentP:Int, count:Int) {

    //println("load segment current page: \(currentPage)")

    api = AuctionAPI(delegate: self)

    if (!self.loading) {

        self.setLoadingState(true)

        println("CP\(currentP)")
        println("TP\(count)")

        if currentPage < toPage{
            println("Enter Condition")
            var times = 0
            api!.searchAuctionLatestFor("null",lotId: "1",page: String(++currentPage))
            println("Current Page After API Call : \(currentPage)")

        }
        else if currentPage > toPage {
            setLoadingState(false)
        }
    }
    else{
        println("Not Loading")
    }

}

// Loading Progress at Table View Footer condition (disabling the table view footer which include loading indicator or not)
func setLoadingState(loading:Bool) {
    self.loading = loading
    self.tableViewFooter.hidden = !loading
}

func didReceiveAPIResults(results: NSDictionary) {
    var resultsArr: NSArray = results["body"] as NSArray
    //fix
    dispatch_async(dispatch_get_main_queue(), {
        self.newItems = AuctionModel.latestWithJSON(resultsArr)
        println("Current Auction Items : \(self.newItems.count)")
        //println("Page: \(self.currentPage) Items \(self.items)")

        if self.currentPage > 1 {
                for item:AuctionModel in self.newItems {
                    self.items.append(item)
                }
        }
        else{
            self.items = self.newItems
        }

        self.currentCount = self.items.count

        println("After Auction Items : \(self.currentCount)")

        self.tableView?.reloadData()
        //Status bar network activity ကို ပိတ်​ရန်/ဖွင့်​ခဲ့​ရင်
        //UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        self.tableView?.hidden = false
    })
}

func doSearchMoreAPIResults(results: JSON){
    if results != nil{
        totalCount = results["header"]["totalCount"].intValue
        currentPage = results["header"]["currentPage"].intValue
        toPage = results["header"]["toPage"].intValue
    }
    println("totalCount : \(totalCount)")
    println("currentPage : \(currentPage)")
    println("toPage : \(toPage)")
}

func didNotReceiveAPIResults(results: Bool){
    var connectionResult : Bool = results
}
}

AuctionAPI.swift

import Foundation

protocol AuctionAPIProtocol{
    func didReceiveAPIResults(results: NSDictionary)
    func didNotReceiveAPIResults(results: Bool)
    func doSearchMoreAPIResults(results:JSON)
}

class AuctionAPI{

var delegate: AuctionAPIProtocol
var urlParameterStringController:URLParameterStringController!

init(delegate: AuctionAPIProtocol){
    self.delegate=delegate
}

func post(path:String,params:Dictionary<String,String>){

    //Parameter Parts.....

    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        .....
        self.delegate.didReceiveAPIResults(jsonData)
        self.delegate.doSearchMoreAPIResults(json)
    })
    task.resume()
}

func searchAuctionLatestFor(token:String,lotId:String,page:String){
    .....
    post(urlPath,params: params)
}
}

我更新了代码,现在我在获得 30 个结果后向下滚动时卡在“正在加载”。实际上它应该加载 636 个结果。

这是我的控制台 output 。 这是我的模拟器,它在第 2 页并卡在加载中。 Fig

现在没有更多的重复结果,但是为什么当我向下滚动以加载更多数据时它不加载更多数据并停留在第 2 页。

最佳答案

我在加载时卡在第 2 页的原因是,在我从“didReceiveAPIResults()”获得结果后,我没有将“setLoadingState()”设置为 false。因此,在将结果附加到项目数组后,做自己.setLoadingState(false) 解决了这个问题,当用户拉起从另一个页面加载更多数据时,它会进入 if(!self.loading) 条件。

谢谢。我不会更新答案,因为我希望所有喜欢我的人都能找到答案。

关于ios - 为什么我的 "pull down to load data"卡在第 2 页而没有加载更多数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30025831/

相关文章:

iOS8 Beta 3 UITableViewCell layoutSubviews 死循环

swift - SKAction.moveBy 不工​​作,我不知道为什么

ios - 如何在 swift 中使用 BLOB 将字节数组 [UInt8] 存储和检索到 sqlite3 数据库中?

ios - 无法执行单击导航栏自定义按钮

ios - 在这种情况下如何测试收据验证?

ios - 复数应用程序 - 使用核心图、幂图或其他绘图?

ios - 如何在 iOS 中滑动 UITableViewCell

ios - 如何在 swift 3 中通过 SearchBar 按电子邮件地址搜索联系人?

uitableview - swift 为 UITableView 加载更多内容

objective-c - 如何使用UCKeyTranslate