为什么我的"拉下来加载数据"陷入第2页而不再加载数据

时间:2015-05-04 08:34:37

标签: ios uitableview swift uiscrollview infinite-scroll

是否存在通过使用json中的new添加旧数据来重新加载新数据的理论?我遇到了解决该问题的问题。我使用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)
}
}

我更新了代码,现在我被困在&#34;正在加载&#34;当我在获得30个结果后向下滚动。实际上它应该加载636个结果。

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

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

didReceiveAPIResults中,您正在设置self.items并将其附加到其中,以便您删除旧数据然后复制它。您只需将新结果附加到现有列表中即可。