Accessing values from JSON Response in swift ios - ios
I have api it returns json response(https://pixabay.com/api/?key=10961259-e4e939648ed5abb6879f1fbbc&q=yellow+flowers&image_type=photo)
I want to access parameters(webformatURL, tags) from the response. I made URL session request and getting data is like below. How can i query and access those parameters from the response in swift. I'm new to programming please suggest me in swift.
//Mark:- Method to fetch data from the url
func getDataFromUrl(){
let url = URL(string: "https://pixabay.com/api/?key=10961259-e4e939648ed5abb6879f1fbbc&q=yellow+flowers&image_type=photo")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "GET"
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if error == nil
{
do
{
let respDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
print("Some Data: \(respDict)")
}
catch let error2 as NSError
{
print(error2)
}
}
})
dataTask.resume()
}
And the response is:
{
"totalHits": 500,
"hits": [
{
"largeImageURL": "https://pixabay.com/get/ea35b70c2afc053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 848,
"imageWidth": 6000,
"id": 3063284,
"user_id": 1564471,
"views": 476351,
"comments": 191,
"pageURL": "https://pixabay.com/en/rose-flower-petal-floral-noble-3063284/",
"imageHeight": 4000,
"webformatURL": "https://pixabay.com/get/ea35b70c2afc053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "rose, flower, petal",
"downloads": 288342,
"user": "annca",
"favorites": 720,
"imageSize": 3574625,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2015/11/27/06-58-54-609_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/01/05/16/24/rose-3063284_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea34b00c2bf5093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 706,
"imageWidth": 2736,
"id": 3113318,
"user_id": 7410713,
"views": 342627,
"comments": 113,
"pageURL": "https://pixabay.com/en/sunflower-nature-flora-flower-3113318/",
"imageHeight": 1824,
"webformatURL": "https://pixabay.com/get/ea34b00c2bf5093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "sunflower, nature, flora",
"downloads": 242156,
"user": "bichnguyenvo",
"favorites": 454,
"imageSize": 1026006,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2017/12/16/10-28-39-199_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/01/28/11/24/sunflower-3113318_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea37b80d21f7033ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 400,
"webformatWidth": 640,
"likes": 434,
"imageWidth": 3200,
"id": 3292932,
"user_id": 2216431,
"views": 184738,
"comments": 34,
"pageURL": "https://pixabay.com/en/sunflower-vase-vintage-retro-wall-3292932/",
"imageHeight": 2000,
"webformatURL": "https://pixabay.com/get/ea37b80d21f7033ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 93,
"tags": "sunflower, vase, vintage",
"downloads": 146666,
"user": "Yuri_B",
"favorites": 593,
"imageSize": 2563708,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/01/15/10-52-15-382_250x250.png",
"previewURL": "https://cdn.pixabay.com/photo/2018/04/05/14/09/sun-flower-3292932_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/eb37b80a2cf7053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 486,
"imageWidth": 5363,
"id": 2295434,
"user_id": 334088,
"views": 54291,
"comments": 33,
"pageURL": "https://pixabay.com/en/spring-bird-bird-tit-spring-blue-2295434/",
"imageHeight": 3575,
"webformatURL": "https://pixabay.com/get/eb37b80a2cf7053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "spring bird, bird, tit",
"downloads": 25018,
"user": "jill111",
"favorites": 548,
"imageSize": 2938651,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/06/27/01-23-02-27_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2017/05/08/13/15/spring-bird-2295434_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ee34b40a2cf41c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_1280.jpg",
"webformatHeight": 360,
"webformatWidth": 640,
"likes": 258,
"imageWidth": 3020,
"id": 715540,
"user_id": 916237,
"views": 82194,
"comments": 31,
"pageURL": "https://pixabay.com/en/yellow-natural-flower-blossom-715540/",
"imageHeight": 1703,
"webformatURL": "https://pixabay.com/get/ee34b40a2cf41c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_640.jpg",
"type": "photo",
"previewHeight": 84,
"tags": "yellow, natural, flower",
"downloads": 39827,
"user": "Wow_Pho",
"favorites": 256,
"imageSize": 974940,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2015/04/07/14-10-15-590_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2015/04/10/00/41/yellow-715540_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea37b00a29fc093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 358,
"webformatWidth": 640,
"likes": 336,
"imageWidth": 2027,
"id": 3215188,
"user_id": 7097598,
"views": 135865,
"comments": 94,
"pageURL": "https://pixabay.com/en/flowers-orange-orange-petals-3215188/",
"imageHeight": 1134,
"webformatURL": "https://pixabay.com/get/ea37b00a29fc093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 83,
"tags": "flowers, orange, orange petals",
"downloads": 93385,
"user": "Candiix",
"favorites": 274,
"imageSize": 399066,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2017/12/06/20-08-45-84_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/03/10/20/26/flowers-3215188_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e830b20928fc093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 419,
"webformatWidth": 640,
"likes": 235,
"imageWidth": 4896,
"id": 1536088,
"user_id": 1195798,
"views": 268764,
"comments": 53,
"pageURL": "https://pixabay.com/en/sunflower-flower-bloom-yellow-1536088/",
"imageHeight": 3208,
"webformatURL": "https://pixabay.com/get/e830b20928fc093ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 98,
"tags": "sunflower, flower, bloom",
"downloads": 40996,
"user": "Couleur",
"favorites": 203,
"imageSize": 5103399,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/09/29/00-20-33-645_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2016/07/23/00/12/sun-flower-1536088_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/eb34b50a2df7083ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 390,
"webformatWidth": 640,
"likes": 306,
"imageWidth": 4000,
"id": 2145539,
"user_id": 2364555,
"views": 36019,
"comments": 27,
"pageURL": "https://pixabay.com/en/crocus-flower-wet-spring-2145539/",
"imageHeight": 2443,
"webformatURL": "https://pixabay.com/get/eb34b50a2df7083ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 91,
"tags": "crocus, flower, wet",
"downloads": 20750,
"user": "pixel2013",
"favorites": 286,
"imageSize": 823922,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/02/25/16-46-24-974_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2017/03/15/09/00/crocus-2145539_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ec33b50e2ce90021d85a5854e74c4f90e275e7dc04b0144591f5c270a4edb2_1280.jpg",
"webformatHeight": 428,
"webformatWidth": 640,
"likes": 436,
"imageWidth": 3872,
"id": 56414,
"user_id": 9003,
"views": 57529,
"comments": 75,
"pageURL": "https://pixabay.com/en/anemone-flower-blossom-bloom-blue-56414/",
"imageHeight": 2592,
"webformatURL": "https://pixabay.com/get/ec33b50e2ce90021d85a5854e74c4f90e275e7dc04b0144591f5c270a4edb2_640.jpg",
"type": "photo",
"previewHeight": 100,
"tags": "anemone, flower, blossom",
"downloads": 20907,
"user": "Albenheim",
"favorites": 364,
"imageSize": 770723,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2012/09/08/21-14-56-990_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2012/09/08/21/51/anemone-56414_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e830b00d20f5023ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 323,
"webformatWidth": 640,
"likes": 211,
"imageWidth": 3861,
"id": 1512813,
"user_id": 2364555,
"views": 63538,
"comments": 22,
"pageURL": "https://pixabay.com/en/lily-flowers-early-flower-garden-1512813/",
"imageHeight": 1952,
"webformatURL": "https://pixabay.com/get/e830b00d20f5023ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 75,
"tags": "lily, flowers, early",
"downloads": 31782,
"user": "pixel2013",
"favorites": 209,
"imageSize": 1037708,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/02/25/16-46-24-974_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2016/07/12/18/54/lily-1512813_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ee37b80a29f11c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_1280.jpg",
"webformatHeight": 416,
"webformatWidth": 640,
"likes": 269,
"imageWidth": 1980,
"id": 729515,
"user_id": 909086,
"views": 33664,
"comments": 17,
"pageURL": "https://pixabay.com/en/flower-beautiful-bloom-blooming-729515/",
"imageHeight": 1288,
"webformatURL": "https://pixabay.com/get/ee37b80a29f11c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_640.jpg",
"type": "photo",
"previewHeight": 97,
"tags": "flower, beautiful, bloom",
"downloads": 21810,
"user": "Bess-Hamiti",
"favorites": 348,
"imageSize": 370390,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2017/09/19/10-02-47-777_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2015/04/19/08/33/flower-729515_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e83cb60d2cf5003ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 372,
"webformatWidth": 640,
"likes": 247,
"imageWidth": 4288,
"id": 1972411,
"user_id": 1777190,
"views": 84036,
"comments": 29,
"pageURL": "https://pixabay.com/en/drip-blossom-bloom-yellow-1972411/",
"imageHeight": 2499,
"webformatURL": "https://pixabay.com/get/e83cb60d2cf5003ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 87,
"tags": "drip, blossom, bloom",
"downloads": 71846,
"user": "susannp4",
"favorites": 244,
"imageSize": 1510459,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2015/12/16/17-56-55-832_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2017/01/11/17/27/drip-1972411_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e834b30829f3053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 338,
"imageWidth": 4752,
"id": 1127174,
"user_id": 1445608,
"views": 93274,
"comments": 24,
"pageURL": "https://pixabay.com/en/sunflower-summer-yellow-nature-1127174/",
"imageHeight": 3168,
"webformatURL": "https://pixabay.com/get/e834b30829f3053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "sunflower, summer, yellow",
"downloads": 55774,
"user": "mploscar",
"favorites": 341,
"imageSize": 3922163,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2016/01/05/14-08-20-943_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2016/01/08/05/24/sunflower-1127174_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e834b2082bf11c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_1280.jpg",
"webformatHeight": 355,
"webformatWidth": 640,
"likes": 167,
"imageWidth": 2410,
"id": 113735,
"user_id": 817,
"views": 91032,
"comments": 29,
"pageURL": "https://pixabay.com/en/rose-flower-yellow-yellow-rose-113735/",
"imageHeight": 1337,
"webformatURL": "https://pixabay.com/get/e834b2082bf11c22d2524518b74d469fe576e0d010ac104491f4c47aaeeeb5bf_640.jpg",
"type": "photo",
"previewHeight": 83,
"tags": "rose, flower, yellow",
"downloads": 13679,
"user": "blizniak",
"favorites": 152,
"imageSize": 299425,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2013/06/28/17-07-05-714_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2013/05/26/12/14/rose-113735_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/e836b00629f5053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 249,
"imageWidth": 4272,
"id": 1319114,
"user_id": 485024,
"views": 87475,
"comments": 24,
"pageURL": "https://pixabay.com/en/girl-flowers-yellow-beauty-nature-1319114/",
"imageHeight": 2848,
"webformatURL": "https://pixabay.com/get/e836b00629f5053ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "girl, flowers, yellow",
"downloads": 41303,
"user": "AdinaVoicu",
"favorites": 263,
"imageSize": 3837334,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/12/07/21-49-54-663_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2016/04/09/23/10/girl-1319114_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea32b30f2bfc023ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 108,
"imageWidth": 6000,
"id": 3720383,
"user_id": 6246704,
"views": 16075,
"comments": 32,
"pageURL": "https://pixabay.com/en/flower-g%C3%A9rbel-yellow-flower-flower-3720383/",
"imageHeight": 4000,
"webformatURL": "https://pixabay.com/get/ea32b30f2bfc023ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "flower gérbel, yellow flower, flower",
"downloads": 9864,
"user": "fernandozhiminaicela",
"favorites": 81,
"imageSize": 2117262,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/06/04/17-13-01-772_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/10/03/03/42/flower-gerbel-3720383_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea35b40f28f3073ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 285,
"imageWidth": 5472,
"id": 3050076,
"user_id": 6663646,
"views": 131773,
"comments": 28,
"pageURL": "https://pixabay.com/en/portrait-girl-fog-flowers-beauty-3050076/",
"imageHeight": 3648,
"webformatURL": "https://pixabay.com/get/ea35b40f28f3073ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "portrait, girl, fog",
"downloads": 92671,
"user": "ThuyHaBich",
"favorites": 283,
"imageSize": 2914111,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2017/11/17/08-35-57-188_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2017/12/30/13/25/portrait-3050076_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ec37b20a20e90021d85a5854e74c4f90e275e7dc04b0144591f5c270a4edb2_1280.jpg",
"webformatHeight": 360,
"webformatWidth": 640,
"likes": 179,
"imageWidth": 1920,
"id": 52358,
"user_id": 5783,
"views": 28923,
"comments": 20,
"pageURL": "https://pixabay.com/en/flower-wild-flower-nature-52358/",
"imageHeight": 1080,
"webformatURL": "https://pixabay.com/get/ec37b20a20e90021d85a5854e74c4f90e275e7dc04b0144591f5c270a4edb2_640.jpg",
"type": "photo",
"previewHeight": 84,
"tags": "flower, wild flower, nature",
"downloads": 10460,
"user": "PeterDargatz",
"favorites": 154,
"imageSize": 172383,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2012/06/22/22-42-41-494_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2012/07/12/14/50/flower-52358_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/eb31b10b2ff2083ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 427,
"webformatWidth": 640,
"likes": 204,
"imageWidth": 6016,
"id": 2404769,
"user_id": 4331363,
"views": 29872,
"comments": 21,
"pageURL": "https://pixabay.com/en/summer-field-nature-cereals-2404769/",
"imageHeight": 4016,
"webformatURL": "https://pixabay.com/get/eb31b10b2ff2083ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 100,
"tags": "summer, field, nature",
"downloads": 12788,
"user": "geraldfriedrich2",
"favorites": 257,
"imageSize": 4290219,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2017/02/22/12-32-00-453_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2017/06/15/10/25/summer-2404769_150.jpg"
},
{
"largeImageURL": "https://pixabay.com/get/ea33b50f21f7043ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_1280.jpg",
"webformatHeight": 426,
"webformatWidth": 640,
"likes": 213,
"imageWidth": 5574,
"id": 3640935,
"user_id": 334088,
"views": 103667,
"comments": 54,
"pageURL": "https://pixabay.com/en/sunflowers-field-woman-yellow-3640935/",
"imageHeight": 3717,
"webformatURL": "https://pixabay.com/get/ea33b50f21f7043ed1584d05fb1d4796ea71e3d71cb80c4090f4c57ca4e4b6b8df_640.jpg",
"type": "photo",
"previewHeight": 99,
"tags": "sunflowers, field, woman",
"downloads": 86701,
"user": "jill111",
"favorites": 186,
"imageSize": 4970597,
"previewWidth": 150,
"userImageURL": "https://cdn.pixabay.com/user/2018/06/27/01-23-02-27_250x250.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/08/29/22/52/sunflowers-3640935_150.jpg"
}
],
"total": 17148
}
You are getting one JSON object with keys:
totalHits
hits
total
In the above three keys, value of https is another JSON array having many json objects inside it. you can get that object by
let respDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
let httpDictArray = respDict["hits"] as! [Any]
for dictionary in httpDictArray{
if let dict = dictionary as? [String:Any]
{
let webFormatUrl = dict["webformatURL"] as! String
let tags = dict["tags"] as! String
}
}
Here tags is a string which is a concatenation of many words separated by comma.
so from tags string you can get the array of tags as
let tagArray = tags.components(separatedBy: ", ")
The Decodable protocol is the most convenient way to parse JSON in Swift 4+
struct Root : Decodable {
let totalHits : Int
let hits : [Hit]
}
struct Hit : Decodable {
let webformatURL : URL
let tags : String
}
func getDataFromUrl() {
let url = URL(string: "https://pixabay.com/api/?key=10961259-e4e939648ed5abb6879f1fbbc&q=yellow+flowers&image_type=photo")
let session = URLSession.shared
let dataTask = session.dataTask(with: url!) { data, response, error in
guard let data = data else { print(error!); return }
do {
let result = try JSONDecoder().decode(Root.self, from: data)
let hits = result.hits
for hit in hits {
print("webformatURL: ", hit.webformatURL, "tags:", hit.tags)
}
} catch {
print(error)
}
}
dataTask.resume()
}
getDataFromUrl()
Note:
An URLRequest is not needed in this case and don't use NSMutableURLRequest in Swift anyway.
Now that you have your response in a dictionary, you can do the following to get the hits:
guard let results = respDict as? [String: Any],
let hits = results["hits"] as? Array<[String:Any]> else {
return
}
Now, when you have the hits, let's transform this array of objects into two array. array of urls, and array of tags.
let urls = hits.flatMap { $0["webformatURL"] as? String }
let tags = hits.flatMap { $0["tags"] as? String }
There you go!
Here is the simple approach,
struct HitResponse: Codable {
var total: Int
var totalHits: Int
var hits: [HitObject]
}
struct HitObject: Codable {
var largeImageURL: String
var webformatHeight: Int
var webformatWidth: Int
var likes: Int
var imageWidth: Int
var id: Int
var user_id: Int
var views: Int
var comments: Int
var pageURL: String
var imageHeight: Int
var webformatURL: String
var type: String
var previewHeight: Int
var tags: String
var downloads: Int
var user: String
var favorites: Int
var imageSize: Int
var previewWidth: Int
var userImageURL: String
var previewURL: String
}
enum APIResponse {
case success(result: Result)
case error(error: Error)
}
struct Result{
var object: Any
}
class APIRequester {
static func request(for url: URL, completionHandler: #escaping (_ response: APIResponse)->Void) {
let sesseion = URLSession.shared
let task = sesseion.dataTask(with: url) { (data, urlResponse, error) in
// data mapping to model
if let lData = data {
do {
let decode = try JSONDecoder().decode(HitResponse.self, from: lData)
let responseMap: APIResponse = .success(result: Result(object: decode))
completionHandler(responseMap)
}catch let mappingError {
let responseMap: APIResponse = .error(error: mappingError)
completionHandler(responseMap)
}
}
//fall back original error
let responseMap: APIResponse = .error(error: error!)
completionHandler(responseMap)
}
task.resume()
}
}
// Usage
let url = URL(string: "https://pixabay.com/api/?key=10961259-e4e939648ed5abb6879f1fbbc&q=yellow+flowers&image_type=photo")
APIRequester.request(for: url!) { (response) in
switch response {
case .success(let result):
if let hitResponse = result.object as? HitResponse {
for hit in hitResponse.hits {
//the final output
print(hit.tags)
print(hit.webformatURL)
print("\n")
}
}
case .error(let error):
// handle error
print("error \(error)")
}
}
Related
How can I download a GIF from a URL In Swift (Gif From Tenor)
I am running into two issues trying to download a Gif from Tenor. In my main app I pass in my API_Key and make a request which in return gives me a ITEMURL: https://tenor.com/view/yes-chuck-norris-approves-thumbs-up-gif-14366055 and a URL: https://tenor.com/8rqJ.gif I am able to open the url on a browser and see the gif but I cannot download it to the app. I have a ViewController that I will post below. I really am looking for a way to successfully download the gif from the tenor url. I was able to make the gif work with a public URL: https://blog.hootsuite.com/wp-content/uploads/2022/06/How-to-Make-a-GIF-1.gif HERE IS MY CODE MY ViewController: import UIKit import FLAnimatedImage class ViewController: UIViewController { let imageView = FLAnimatedImageView() let button = UIButton() let spinner = UIActivityIndicatorView(style: .large) override func viewDidLoad() { super.viewDidLoad() setupButton() setupSpinner() setupImageView() } private func setupButton() { button.frame = CGRect(x: 100, y: 100, width: 100, height: 50) button.backgroundColor = .black view.addSubview(button) button.addTarget(self, action: #selector(getGif), for: .touchUpInside) } private func setupSpinner() { view.addSubview(spinner) spinner.center = view.center } private func setupImageView() { imageView.frame = CGRect(x: 300, y: 600, width: 200, height: 200) view.addSubview(imageView) imageView.center = view.center imageView.contentMode = .scaleAspectFit } #objc func getGif() { // Create a URL for the GIF spinner.startAnimating() guard let url = URL(string: "https://blog.hootsuite.com/wp-content/uploads/2022/06/How-to-Make-a-GIF-1.gif") else { return } let task = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in guard let this = self else { return } if let error = error { print(error) return } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { print("Invalid Response") return } //make sure there is data guard let data = data else { print("No Data returned") return } let animatedImage = FLAnimatedImage(animatedGIFData: data) DispatchQueue.main.async { this.spinner.stopAnimating() this.button.isHidden = true this.imageView.animatedImage = animatedImage } } task.resume() } } I think it would be wise to mention I am using FLAnimatedImage to help with showing the Gif. I am open to other solutions.
I found my problem with the Tenor URL. The reason I was not able to show it on the app is that I was showing the URL that is on Tenor's site which also has other GIFs on there as well. After looking over the response from the API I noticed it gives back a bunch of media formats. (I will paste the response below if anyone cares to see) I noticed the gif media format and opened that in my browser and found out that this URL took me to ONLY this jif with no other content on the page. I rewrote my Struct model to match this and BOOM... problem solved. Data Model Struct: import Foundation // MARK: - Content struct Content: Decodable { let results: [Result] } // MARK: - Result struct Result: Decodable { let media_formats: MediaFormats } // MARK: - MediaFormats struct MediaFormats: Decodable { let gif: GIF } // MARK: - GIF struct GIF: Decodable { let url: String } Response From API call: { "results": [ { "id": "7321207095287125549", "title": "texas", "media_formats": { "tinywebm": { "url": "https://media.tenor.com/ZZonEFGoli0AAAP3/chuck-norris-walker-texas-ranger.webm", "duration": 0, "preview": "", "dims": [ 320, 240 ], "size": 57989 }, "tinygifpreview": { "url": "https://media.tenor.com/ZZonEFGoli0AAAAF/chuck-norris-walker-texas-ranger.png", "duration": 0, "preview": "", "dims": [ 220, 165 ], "size": 0 }, "mp4": { "url": "https://media.tenor.com/ZZonEFGoli0AAAPo/chuck-norris-walker-texas-ranger.mp4", "duration": 2.3, "preview": "", "dims": [ 400, 300 ], "size": 139907 }, "webm": { "url": "https://media.tenor.com/ZZonEFGoli0AAAPs/chuck-norris-walker-texas-ranger.webm", "duration": 0, "preview": "", "dims": [ 400, 300 ], "size": 65667 }, "nanogifpreview": { "url": "https://media.tenor.com/ZZonEFGoli0AAAAT/chuck-norris-walker-texas-ranger.png", "duration": 0, "preview": "", "dims": [ 120, 90 ], "size": 0 }, "nanomp4": { "url": "https://media.tenor.com/ZZonEFGoli0AAAP2/chuck-norris-walker-texas-ranger.mp4", "duration": 2.3, "preview": "", "dims": [ 150, 112 ], "size": 45110 }, "tinygif": { "url": "https://media.tenor.com/ZZonEFGoli0AAAAM/chuck-norris-walker-texas-ranger.gif", "duration": 0, "preview": "", "dims": [ 220, 165 ], "size": 266545 }, "gifpreview": { "url": "https://media.tenor.com/ZZonEFGoli0AAAAe/chuck-norris-walker-texas-ranger.png", "duration": 0, "preview": "", "dims": [ 400, 300 ], "size": 37163 }, "nanogif": { "url": "https://media.tenor.com/ZZonEFGoli0AAAAS/chuck-norris-walker-texas-ranger.gif", "duration": 0, "preview": "", "dims": [ 120, 90 ], "size": 103784 }, "mediumgif": { "url": "https://media.tenor.com/ZZonEFGoli0AAAAd/chuck-norris-walker-texas-ranger.gif", "duration": 0, "preview": "", "dims": [ 400, 300 ], "size": 991245 }, "tinymp4": { "url": "https://media.tenor.com/ZZonEFGoli0AAAP1/chuck-norris-walker-texas-ranger.mp4", "duration": 2.3, "preview": "", "dims": [ 320, 240 ], "size": 127441 }, "loopedmp4": { "url": "https://media.tenor.com/ZZonEFGoli0AAAPo/chuck-norris-walker-texas-ranger.mp4", "duration": 2.3, "preview": "", "dims": [ 400, 300 ], "size": 139907 }, "gif": { "url": "https://media.tenor.com/ZZonEFGoli0AAAAC/chuck-norris-walker-texas-ranger.gif", "duration": 0, "preview": "", "dims": [ 400, 300 ], "size": 1520206 }, "nanowebm": { "url": "https://media.tenor.com/ZZonEFGoli0AAAP4/chuck-norris-walker-texas-ranger.webm", "duration": 0, "preview": "", "dims": [ 150, 112 ], "size": 56817 } }, "created": 1460746269.6868651, "content_description": "Texas GIF", "itemurl": "https://tenor.com/view/chuck-norris-walker-texas-ranger-gif-5336135", "url": "https://tenor.com/wykR.gif", "tags": [ "Chuck Norris", "Walker Texas Ranger" ], "flags": [], "hasaudio": false } ], "next": "CAEQ79qe_OSJ_AIaHgoKAD-_xhumWuxY_xIQOpL78_1184rUPMB1AAAAADAy" }
Binding JSON data to TableView and CollectionView
I am trying to create a table view with a collection view in each cell. My JSON structure is like Main Menu title for the tv cell and in each main object, I receive a submenu, whose data I want to use in the collection view. The issue I am facing is in using indexes of table cell and collection cell to get the nested data. Here is my JSON "MainMenu": [ { "ID": 8, "MasterID": 12, "Title": "Payment", "Image": "image.png", "SubMenu": [ { "ID": 9, "Title": "My Bill", "Image": "image.png" }, { "ID": 10, "Title": "Electricity ", "Image": "image.png" }, { "ID": 11, "Title": "Gas", "Image": "image.png" }, { "ID": 12, "Title": "Telephone", "Image": "image.png" }, { "ID": 13, "Title": "Water", "Image": "image.png" } ] }, { "ID": 40, "MasterID": 14, "Title": "Services", "Image": "image.png", "SubMenu": [ { "ID": 32, "Title": "Upload Slip", "Image": "image.png" }, { "ID": 41, "Title": "SRY (Self Reliant Youth)", "Image": "image.png" }, { "ID": 42, "Title": "Dollor Product Purchase ", "Image": "image.png" }, { "ID": 43, "Title": "ARY Coin Redemption", "Image": "image.png" }, { "ID": 44, "Title": "Pay Via QR", "Image": "image.png" }, { "ID": 45, "Title": "Card Request", "Image": "image.png" } ] }, { "ID": 14, "MasterID": 8, "Title": "Mobile Balance", "Image": "image.png", "SubMenu": [ { "ID": 15, "Title": "My Mobile", "Image": "image.png" }, { "ID": 16, "Title": "Mobilink", "Image": "image.png" }, { "ID": 17, "Title": "Telenor", "Image": "image.png" }, { "ID": 18, "Title": "Ufone", "Image": "image.png" }, { "ID": 19, "Title": "Warid", "Image": "image.png" }, { "ID": 20, "Title": "Zong", "Image": "image.png" } ] }, { "ID": 46, "MasterID": 6, "Title": "Help", "Image": "image.png", "SubMenu": [ { "ID": 47, "Title": "Call", "Image": "image.png" }, { "ID": 48, "Title": "Chat", "Image": "image.png" }, { "ID": 49, "Title": "Email", "Image": "image.png" }, { "ID": 50, "Title": "Others", "Image": "image.png" }, { "ID": 51, "Title": "VAS / SMS", "Image": "image.png" } ] }, { "ID": 21, "MasterID": 5, "Title": "Fund Transfer", "Image": "image.png", "SubMenu": [ { "ID": 22, "Title": "To Other ARY Wallet", "Image": "image.png" }, { "ID": 23, "Title": "To Bank Account", "Image": "image.png" } ] }, { "ID": 34, "MasterID": 1, "Title": "$ & MilliGold Deal", "Image": "image.png", "SubMenu": [ { "ID": 35, "Title": "$ Deposit", "Image": "image.png" }, { "ID": 36, "Title": "$ Purchase", "Image": "image.png" }, { "ID": 37, "Title": "$ Time Games", "Image": "image.png" }, { "ID": 38, "Title": "Scan for Bid", "Image": "image.png" } ] } ], "CustomerAccountInformation": [] } Please guide me how can I use my JSON objects each in different tablecell. Here is what I have tried: TVCell cell.titleLabel.text = menu?.mainMenu?[indexPath.row].title ?? "Our services" CollectionCell cell.image.af_setImage(withURL: URL.init(string: (menu?.mainMenu?[indexPath.row].subMenu?[indexPath.row].image)!)!)
First, in your tableview cell, set the tag of the collectionview to indexPath.row func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : TVCell = tableview.dequeueReusableCell(withIdentifier: "TVCell", for: indexPath) as! TVCell cell.myCollectionView.tag = indexPath.row return cell } Now in your collectionview cell you can parse the data like following let index = cell.tag cell.image.af_setImage(withURL: URL.init(string: (menu?.mainMenu?[index].subMenu?[indexPath.row].image)!)!)
How to load that JSON on tableview?
I have problem with parse json to collectionview That is my JSON: { "statusCode": 200, "message": "Список курсов", "content": [ { "id": 1, "slug": "kurs-a1", "title": "Курс А1", "can_access": 1, "passed": 1, "sections": [ { "id": 1, "slug": "razdel-1", "title": "Раздел 1", "can_access": 1, "passed": 1, "lessons": [ { "id": 1, "position": 1, "title": "Сәлемдесу", "slug": "salemdesu", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 1, "passed": 1 }, { "id": 3, "position": 2, "title": "Танысу", "slug": "tanysu", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 1, "passed": 1 } ] }, { "id": 2, "slug": "razdel-2", "title": "Раздел 2", "can_access": 1, "passed": 0, "lessons": [ { "id": 4, "position": 3, "title": "Бұл – менің отбасым", "slug": "bul-menin-otbasym", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 1, "passed": 0 }, { "id": 5, "position": 4, "title": "Жасы нешеде?", "slug": "zhasy-neshede", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 1, "passed": 0 } ] }, { "id": 3, "slug": "razdel-3", "title": "Раздел 3", "can_access": 0, "passed": 0, "lessons": [ { "id": 7, "position": 5, "title": "Туған күн", "slug": "tugan-kun", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 }, { "id": 9, "position": 6, "title": "Құттықтау", "slug": "kuttyktau", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 } ] }, { "id": 4, "slug": "razdel-4", "title": "Раздел 4", "can_access": 0, "passed": 0, "lessons": [ { "id": 10, "position": 7, "title": "Адам келбеті", "slug": "adam-kelbeti", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 }, { "id": 12, "position": 8, "title": "Адамның мінез-құлқы", "slug": "adamnyn-minez-kulky", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 } ] }, { "id": 5, "slug": "razdel-5", "title": "Раздел 5", "can_access": 0, "passed": 0, "lessons": [ { "id": 13, "position": 9, "title": "Менің мамандығым", "slug": "menin-mamandygym", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 }, { "id": 15, "position": 10, "title": "Кім болып жұмыс істейді?", "slug": "kim-bolyp-zhumys-istejdi", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 } ] }, { "id": 6, "slug": "razdel-6", "title": "Раздел 6", "can_access": 0, "passed": 0, "lessons": [ { "id": 16, "position": 11, "title": "Жұмыс орны", "slug": "zhumys-orny", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 }, { "id": 17, "position": 12, "title": "Жұмыс күні", "slug": "zhumys-kuni", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 } ] }, { "id": 7, "slug": "razdel-7", "title": "Раздел 7", "can_access": 0, "passed": 0, "lessons": [ { "id": 19, "position": 13, "title": "Тесты ЦОР-а", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 }, { "id": 20, "position": 14, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 } ] }, { "id": 8, "slug": "razdel-8", "title": "Раздел 8", "can_access": 0, "passed": 0, "lessons": [ { "id": 22, "position": 15, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 }, { "id": 23, "position": 16, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 } ] }, { "id": 9, "slug": "razdel-9", "title": "Раздел 9", "can_access": 0, "passed": 0, "lessons": [ { "id": 25, "position": 17, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 }, { "id": 27, "position": 18, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 } ] }, { "id": 10, "slug": "razdel-10", "title": "Раздел 10", "can_access": 0, "passed": 0, "lessons": [ { "id": 28, "position": 19, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 }, { "id": 29, "position": 20, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 } ] }, { "id": 11, "slug": "razdel-11", "title": "Раздел 11", "can_access": 0, "passed": 0, "lessons": [ { "id": 32, "position": 21, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 }, { "id": 33, "position": 22, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 } ] }, { "id": 12, "slug": "razdel-12", "title": "Раздел 12", "can_access": 0, "passed": 0, "lessons": [ { "id": 34, "position": 23, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 }, { "id": 35, "position": 24, "title": "Тесты", "slug": "testy", "image": "https://tilqural.kz/assets/img/default-lesson-icon.png", "can_access": 0, "passed": 0 } ] } ] } ] } I decode it and i want parse it to collectionview. How can i get content [{sections[{lessons[{title}]}]}]? I made a request func numberOfSections(in collectionView: UICollectionView) -> Int { return arrData1.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let dn = arrData1[section] let st = dn.sections?[section] return (st?.lessons?.count)! } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "main_cell", for: indexPath) as! MainCollectionViewCell cell.lesson_text_1.text = arrData1.first?.sections?[indexPath.item].title // cell.lesson_img_1.image = UIImage(named: lesson_image_1[indexPath.row]) // cell.lesson_text_1.text = lesson_text_1[indexPath.row] return cell } but it return 2 cell to me But i need 24 lessons! Thank you Decoding struct Welcome: Codable { let statusCode: Int let message: String let content: [Content] } struct Content: Codable { let id: Int let slug, title: String let canAccess: Int? let passed: Int let sections: [Content]? let lessons: [Lesson]? enum CodingKeys: String, CodingKey { case id, slug, title case canAccess = "can_access" case passed, sections case lessons = "lessons" } } struct Lesson: Codable { let id, position: Int let title, slug: String let image: String let canAccess: Int? let passed: Int enum CodingKeys: String, CodingKey { case id, position, title, slug, image case canAccess = "can_access" case passed } } api call function let mData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in guard let data = data else { return } do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let data_new = try decoder.decode(Welcome.self, from: data) DispatchQueue.main.async { self.tableview.reloadData() self.arrData1 = data_new.content print(data_new) } } catch { print("Error in CheckNew is : \n\(error)") } } mData.resume() enter image description here
Although the JSON structure is quite similar I recommend to use separate structs for Section and Lesson. Another benefit is you get rid of all optionals struct Welcome: Codable { let statusCode: Int let message: String let content: [Content] } struct Content: Codable { let id: Int let slug, title: String let canAccess: Int let passed: Int let sections: [Section] } struct Section: Codable { let id: Int let title, slug: String let canAccess: Int let passed: Int let lessons: [Lesson] } struct Lesson: Codable { let id, position: Int let title, slug: String let image: URL let canAccess: Int let passed: Int } As you are using the .convertFromSnakeCase strategy all coding keys are redundant.
Decode JSON Data on Swift 4 returns nil
I'm trying to decode my json data with below function. I had different Json format at first and It was working but whenI change json format, It started not to work. I try to do changes also in Structure code but nothing worked. What Am I missing? (Code is for first Json format so It needs to be work on second format too) First JSON: { "status": 200, "results": [ { "group_matched": false, "distance_mi": 4, "content_hash": "1rT2lirUapfrYIYxSR2u0GtmRSLPsVki9kFj4ugs8JIq6", "common_friends": [], "common_likes": [], "common_friend_count": 0, "common_like_count": 0, "connection_count": 0, "_id": "5a2805ba779f34267d32d8b0", "bio": "", "birth_date": "1997-12-09T16:28:29.761Z", "name": "John", }, Second JSON: { "meta": { "status": 200 }, "data": { "results": [ { "type": "user", "user": { "_id": "545001b33bf179416a30bf7f", "bio": "Ä°nstagram:", "birth_date": "1992-12-09T17:12:49.957Z", "name": "", "photos": [ { "id": "2eb1beec-6180-4d58-90fd-5f076da96af9", "url": "", "processedFiles": [ { "url": "", "height": 640, "width": 640 }, { "url": "", "height": 320, "width": 320 }, { "url": "", "height": 172, "width": 172 }, { "url": "", "height": 84, "width": 84 } ] }, { "id": "89d2bc07-d244-457b-b610-26ecd4e9e86d", "url": "", "processedFiles": [ { "url": "", "height": 640, "width": 640 }, { "url": "", "height": 320, "width": 320 }, { "url": "", "height": 172, "width": 172 }, { "url": "", "height": 84, "width": 84 } ] }, { "id": "0fcafc7e-d6e7-4cc5-891a-735971d6a5b2", "url": "", "processedFiles": [ { "url": "", "height": 640, "width": 640 }, { "url": "g", "height": 320, "width": 320 }, { "url": "", "height": 172, "width": 172 }, { "url": "", "height": 84, "width": 84 } ] }, { "id": "bac74531-09e7-4c5b-ac6c-cab36c4be587", "url": "", "processedFiles": [ { "url": "", "height": 640, "width": 640 }, { "url": "", "height": 320, "width": 320 }, { "url": "", "height": 172, "width": 172 }, { "url": "", "height": 84, "width": 84 } ] }, { "id": "3c216244-946a-4c58-8670-cc12c05801cb", "url": "", "processedFiles": [ { "url": "", "height": 640, "width": 640 }, { "url": "", "height": 320, "width": 320 }, { "url": "", "height": 172, "width": 172 }, { "url": "", "height": 84, "width": 84 } ] }, { "id": "-8672-488d-8b7e-f30b4560c56b", "url": "", "processedFiles": [ { "url": "", "height": 640, "width": 640 }, { "url": "", "height": 320, "width": 320 }, { "url": "", "height": 172, "width": 172 }, { "url": "", "height": 84, "width": 84 } ] } ], "gender": 1, Struct Code: struct Photo: Codable{ var url: String? var processedFiles: [processedFiles]? } struct User: Codable{ var group_matched: Bool? var distance_mi: Int? var common_friend_count: Int? var name:String? var profile_picture: String? var instagram_id: String? var photos: [Photo]? } class Results : Codable { var results: [User] = [] static let sharedResults = Results() private init() { } var type: String? func populateData(sender: Results){ print(sender) results += sender.results } } Decode Code: let jsonData = JSON(data: response.data!) let jsonData2 = try? JSONSerialization.data(withJSONObject: jsonData["data"].object) print(JSON(data: jsonData2!)) let decoder = JSONDecoder() var response_class = Results.sharedResults response_class = try decoder.decode(Results.self, from: jsonData2!) Results.sharedResults.populateData(sender: response_class) EDIT: I edit second JSON, It now has array of array. How Can I implement decoder keys for that second array?
In this case I would write a custom initializer with nestedContainer to include the user dictionary into the parent object let jsonString = """ { "meta": { "status": 200 }, "data": { "results": [ { "type": "user", "user": { "_id": "545001b33bf179416a30bf7f", "bio": "Ä°nstagram:hello", "birth_date": "1992-12-09T17:12:49.957Z", "name": "Hello" }, "group_matched": false, "distance_mi": 4 } ] } } """ struct Root : Decodable { let meta : [String:Int] let data : Result } struct Result : Decodable { let results : [User] } struct User : Decodable { let type : String let groupMatched : Bool let distanceMi : Int let id, bio, birthDate, name : String private enum CodingKeys : String, CodingKey { case type, user, groupMatched = "group_matched", distanceMi = "distance_mi" } private enum UserKeys: String, CodingKey { case id = "_id", bio, birthDate = "birth_date", name } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) type = try container.decode(String.self, forKey: .type) groupMatched = try container.decode(Bool.self, forKey: .groupMatched) distanceMi = try container.decode(Int.self, forKey: .distanceMi) let userInfo = try container.nestedContainer(keyedBy: UserKeys.self, forKey: .user) id = try userInfo.decode(String.self, forKey: .id) bio = try userInfo.decode(String.self, forKey: .bio) birthDate = try userInfo.decode(String.self, forKey: .birthDate) name = try userInfo.decode(String.self, forKey: .name) } } do { let data = Data(jsonString.utf8) let decoder = JSONDecoder() let root = try decoder.decode(Root.self, from: data) print(root) } catch { print("error: ", error) }
By making the result of JSONDecoder().decode an optional (try?), you are ensuring that you get nil if the decoding goes wrong. You can catch decoding related issues quickly by implementing proper catch blocks. E.g.: do { let decoder = JSONDecoder() let messages = try decoder.decode(Results.self, from: data) print(messages as Any) } catch DecodingError.dataCorrupted(let context) { print(context) } catch DecodingError.keyNotFound(let key, let context) { print("Key '\(key)' not found:", context.debugDescription) print("codingPath:", context.codingPath) } catch DecodingError.valueNotFound(let value, let context) { print("Value '\(value)' not found:", context.debugDescription) print("codingPath:", context.codingPath) } catch DecodingError.typeMismatch(let type, let context) { print("Type '\(type)' mismatch:", context.debugDescription) print("codingPath:", context.codingPath) } catch { print("error: ", error) } Not a direct answer to your question, but surely will reduce other's time to understand which part of decoding is going wrong.
Convert Array<CustomObject> to JSON
I hava a problem I can't convert array to JSON in SWIFT 3.0 . I am using ObjectMapper My object class OrderItem: Mappable { required init?(map: Map) { } init() { } var oi_id: Int? = 0 var quantity: Double? = 0.0 var discount: Double = 0.0 var sku: Int? = 0 var orderId: Int? = 0 var Product: Product? var isAdd: Bool = false var isMissing: Bool! func mapping(map: Map) { oi_id <- map["oi_id"] quantity <- map["quantity"] discount <- map["discount"] orderId <- map["orderId"] Product <- map["Product"] isAdd <- map["isAdd"] isMissing <- map["isMissing"] }} Convert/ generating the result JSON : var jsonArrayOrderItem = arrayOrderItem.toJSON() Result JSON after convert . JSON is wrong :( [["oi_id": 0, "isAdd": false, "quantity": 1.0, "Product": ["isHot": false, "discount": 50.0, "description": "description", "Acronym": "kg", "priceWithDiscount": 0.62, "bigValue": 1.0, "sku": 14, "Name": "Green Apples", "Price": 1.23, "IsFavorite": true, "smallValue": 0.20000000000000001, "Category": ["bigImageUrl": "https://i.imgur.com/7R3sFnP.png", "ImageUrl": "https://i.imgur.com/NJP4CuA.png", "cat_id": 11, "Name": "Fruits & vegetables", "Products": []], "MeasurementUnitId": 0, "ImageUrl": "https://s22.postimg.org/5992ux3j5/Green_apples.jpg", "CategoryId": 11, "Brand": ["brand_id": 8, "name": "Arbella", "imageUrl": "http://i.imgur.com/xx5ZAgL.jpg", "Products": []]], "orderId": 0, "discount": 0.0], ["oi_id": 0, "isAdd": false, "quantity": 1.0, "Product": ["isHot": false, "discount": 50.0, "description": "description", "Acronym": "kg", "priceWithDiscount": 0.62, "bigValue": 1.0, "sku": 17, "Name": "Mango", "Price": 1.23, "IsFavorite": true, "smallValue": 0.20000000000000001, "Category": ["bigImageUrl": "https://i.imgur.com/7R3sFnP.png", "ImageUrl": "https://i.imgur.com/NJP4CuA.png", "cat_id": 11, "Name": "Fruits & vegetables", "Products": []], "MeasurementUnitId": 0, "ImageUrl": "https://s22.postimg.org/4om6zb2zl/Mango.jpg", "CategoryId": 11, "Brand": ["brand_id": 8, "name": "Arbella", "imageUrl": "http://i.imgur.com/xx5ZAgL.jpg", "Products": []]], "orderId": 0, "discount": 0.0]]
try for Swift 4.0 - It has inbuilt JSONDecoder.