I have the following problem I need to retrieve an array of URL's from a JSON Object in order to download all the pictures of the products from an e-commerce site in my app.
The JSON I get looks like this:
[
{
........
........
.........
........
"images": [
{
"id": 976,
"date_created": "2016-08-10T15:16:49",
"date_modified": "2016-08-10T15:16:49",
"src": "https://i2.wp.com/pixan.wpengine.com/wp-content/uploads/2016/07/canasta-familia.jpg?fit=600%2C600&ssl=1",
"name": "canasta-familia",
"alt": "",
"position": 0
}
],
.......
.......
.......
So far I've been able to get only one string from the array doing this.
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
.responseJSON { response in
if let jsonValue = response.result.value {
let jsonObject = JSON(jsonValue)
var jsonArray = jsonObject[0]["images"][0]["src"].stringValue
print(jsonArray)
}
}
which gives me this
https://xx.xx.xx/xxxx.xxxxx.xxxx/xx-xxxxx/uploads/2016/07/canasta-familia.jpg?fit=600%2C600&ssl=1
But what I need is to access all the elements inside "images" & "src" not just the first element of the index of both.
How can I do this?
Any ideas?
The following lines of code should work as I've tested myself with an actual dataset.
import Alamofire
import SwiftyJSON
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
.responseJSON { response in
if let jsonValue = response.result.value {
let jsonObject = JSON(jsonValue)
if let array = jsonObject.array {
for i in 0..<array.count {
if let images = array[i]["images"].array {
for i in 0..<images.count {
let src = images[i]["src"]
print(src) // save src in an array or whatever
}
}
}
}
}