具有表视图的分页API

时间:2015-11-17 09:56:56

标签: ios swift alamofire

我正在研究从分页API获取数据的应用。当用户滚动时,我想显示更多数据。我有点卡在我现在的位置。这是相关的API服务:

struct APIService {
private static let baseURL = "api.com"
private static let clientID = "1234"
private static let clientSecret = "1234"

private enum ResourcePath: CustomStringConvertible {
    case Stream
    case Community

    var description: String {
        switch self {
        case .Stream: return "/api/posts"
        }
    }
}

class PostsWrapper {
    var total_pages: Int?
    var next_page: Int?
    var previous_page: Int?
}


static func getPosts(page: Int, wrapper: PostsWrapper?, result: ([JSON]) -> ()) {
    getAccessToken()

    let urlString = baseURL + ResourcePath.Stream.description + "?page=\(page)"

    let parameters = [
        "client_id": clientID,
        "client_secret": clientSecret,
    ]

    Alamofire.request(.GET, urlString, parameters: parameters)
        .responseJSON { response in
            if let json = response.result.value {
                let jsonObj = SwiftyJSON.JSON(json ?? [])

                if let data = jsonObj["posts"].arrayValue as [SwiftyJSON.JSON]? {
                    let posts = data
                    result(posts)
                }

                let wrapper = PostsWrapper()
                wrapper.next_page = jsonObj["pagination"]["next_page"].int
                wrapper.previous_page = jsonObj["pagination"]["previous_page"].int
                wrapper.total_pages = jsonObj["pagination"]["total_pages"].int

                print(wrapper.total_pages)

            }
    }
}

}

Post View Controller:

func loadPosts(page: Int) {
    APIService.getPosts(1) { (JSON) -> () in
        self.userStream = JSON

        self.tableView!.reloadData()

        Loading.stop()

    }
}

任何方向都可以加载帖子的下一页并在表格视图中显示。

1 个答案:

答案 0 :(得分:1)

您需要在willDisplayCell方法中检查条件,如下所示

// fade in .navbar
$(function () {
    // hide .navbar first
    $("#header").hide();
    $(window).scroll(function () {
        // set distance user needs to scroll before we start fadeIn
        if ($(this).scrollTop() > 100) {
            $("#header").slideDown("slow"); //you can use fadeIn();
        } else {
            $("#header").slideUp('slow'); // you can use fadeOut();
        }
    });
});