【问题标题】:Why my "pull down to load data" stuck at page 2 without loading anymore data为什么我的“下拉加载数据”卡在第 2 页而不加载更多数据
【发布时间】:2015-05-04 08:34:37
【问题描述】:

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

我的 json 标头包括“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 页。

【问题讨论】:

  • 做一些调试,记录接收和发送的页码,告诉我们它们是什么。您需要本地化问题,而不是只发布所有代码并说“找到我的问题”
  • 我将代码更新为更少更简单。我也遇到了问题,但我不知道如何解决它。我认为“scrollViewDidScroll”方法有问题,用户向下滚动它会加载更多结果通过调用“loadSegment”。问题是我有第 2 页的 30 个结果循环 1-15 和 1-15 并覆盖第一页 1 15 结果

标签: ios uitableview swift uiscrollview infinite-scroll


【解决方案1】:

我在加载时停留在第 2 页的原因是,在我从“didReceiveAPIResults()”获得结果后,我没有将“setLoadingState()”设置为 false。所以在将结果附加到 items Array 之后,做 self .setLoadingState(false) 解决了问题,当用户拉起从另一个页面加载更多数据时,它将进入 if(!self.loading) 状态。

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

【讨论】:

    【解决方案2】:

    didReceiveAPIResults 中,您正在设置self.items 并附加到它,因此您正在删除旧数据然后复制它。您应该简单地将新结果附加到现有列表中。

    【讨论】:

    • @Wain 先生,感谢您的建议和帮助。我非常感谢。我已经更新了代码。我已经解决了数据重复问题。但是,为什么我的程序卡在“加载中" 在我从第 2 页向下滚动之后。
    • 您需要记录它正在使用的页码,我不知道服务器返回的页面详细信息。它总是加载第 1 页还是说没有更多的页面要加载。需要调试...
    • 感谢@Wain,调试帮助我找出答案。但是,我用老式的 println() 找出来,因为我不能很好地使用调试。我现在已经解决了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多