Using Alamofire and SwiftyJSON to retrieve some JSON is trivial:
Given JSON for example
{
"results": [
{
"id": "123",
"name": "Bob"
},
{
"id": "456",
"name": "Sally"
}
}
This function will work:
func loadSomeJSONData() {
Alamofire.request(.GET, "http://example.com/json/")
.responseJSON { (_, _, data, _) in
let json = JSON(data!)
if let firstName = json["results"][0]["name"].string {
println("first name: \(firstName)")
}
}
}
All is well and good. My problem arises when I need to load JSON from the paged API, that is, when data is collected from several calls to the API endpoint, where the JSON looks larger:
{
"currentPage": "1",
"totalPages": "6"
"results": [
{
"id": "123",
"name": "Bob"
},
{
"id": "456",
"name": "Sally"
}
]
}
and then the next block will look like this:
{
"currentPage": "2",
"totalPages": "6"
"results": [
{
"id": "789",
"name": "Fred"
},
{
"id": "012",
"name": "Jane"
}
]
}
In this case, I can recursively call the function to collect all the "pages", but I'm not sure how to correctly assemble all the JSON fragments:
func loadSomeJSONDataFromPagedEndPoint(page : Int = 1) {
Alamofire.request(.GET, "http://example.com/json/" + page)
.responseJSON { (_, _, data, _) in
let json = JSON(data!)
if let totalPages = json["totalPages"].description.toInt() {
if let currentPage = json["currentPage"].description.toInt() {
let pageOfJSON = json["results"]
if currentPage < totalPages {
self.loadSomeJSONDataFromPagedEndPoint(page: currentPage+1)
} else {
}
}
}
var allJSON
loadSomeJSONDataFromPagedEndPoint()
What I would like to do is to ensure that part of the "results" of each JSON response is ultimately assembled into one array of objects (objects { "id": "123", "name": "Bob"})
: , json["totalPages"].description.toInt(), totalPages, ?