Siesta不提供任何特殊的分页处理.分页URL的行为与其他URL一样:每个URL都是唯一的资源.Siesta没有任何黑魔法将来自不同URL的响应合并到单个资源中.
换句话说,如果您的分页方案看起来像/dingbats?page=3&per_page=10,那么Siesta认为"每页10页的dingbats第3页"是单一资源.如果你的分页方案看起来像/dingbats?since_serial_num=31415&max=20,那么Siesta将有一个资源"自序列号31415以来最多20个dingbats".
这在实践中意味着什么?例如,假设您的API返回一个X-Next-Page标题(Github的分页方案的简化风格),并且您希望将结果合并到一个无限可滚动的表视图中.
你可能会这样做:
private var firstPageOfDingbats: Resource?\nprivate var dingbats: [Dingbat] = []\nprivate var dingbatsDisplayed: Int = 1\n\nfunc resourceChanged(resource: Resource, event: ResourceEvent) {\n refreshPages()\n}\n\nfunc refreshPages() {\n // Naive implementation reconstructs the entire dingats array\n // with each update \xe2\x80\x94 which is probably just fine, since array\n // concatenation is cheap.\n\n dingbats.removeAll()\n\n var nextPage = firstPageOfDingbats\n while let curPage = nextPage {\n // This is a noop if data is up to date, but triggers a\n // that runs down the list if it needs updating.\n\n curPage.loadIfNeeded()\n\n // Assuming you\xe2\x80\x99ve set up a content transformer to parse\n // the response as [Dingbat], you can pull them out of\n // the Resource cheaply.\n\n dingbats.appendContentsOf(\n curPage.contentAsType(ifNone: [Dingbat]()))\n\n // Don\xe2\x80\x99t fetch everything if we\xe2\x80\x99ve covered as far as the\n // user has scrolled.\n\n if dingbats.count >= dingbatsDisplayed {\n break\n }\n\n // If we have data and there\xe2\x80\x99s another page, keep going!\n\n nextPage = curPage.optionalRelative(\n curPage.latestData?.header("X-Next-Page"))\n }\n\n tableView.reloadData()\n}\n\noverride func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return dingbats.count\n}\n// etc.\n\n// Add code to increase dingbatsDisplayed and call refreshPages()\n// when user scrolls to the bottom\nRun Code Online (Sandbox Code Playgroud)
如果已经存在数据并且所有内容都是最新的,Siesta的缓存会使页面的这种天真遍历运行得非常快,但是当事情过时时会触发一系列更新.
例如,如果您知道旧条目永远不会更改,而新条目只会出现在顶部,则可以进行更智能的阵列更新.这取决于您使用的特定API及其所做的保证.
如果您有一个复杂的更新方案,并希望精确控制所请求的内容以及结果如何保存在内存中,那么您可能希望完全绕过Siesta的资源缓存.但是,您不需要放弃Siesta来做到这一点!要回归到更传统的基于请求的方法,请使用Resource.request(\xe2\x80\xa6)方法而不是load()和loadIfNeeded():
paginatedResource.request(.GET).success { newData in \xe2\x80\xa6 }\nRun Code Online (Sandbox Code Playgroud)
这使您可以paginatedResource自己管理请求,同时仍然使用Siesta的缓存来处理API的其他部分.