在Swift iOS中从JSON响应访问值

时间:2018-12-11 17:23:26

标签: ios json swift

我有api,它返回json响应(https://pixabay.com/api/?key=10961259-e4e939648ed5abb6879f1fbbc&q=yellow+flowers&image_type=photo

我想从响应中访问参数( webformatURL,标记)。我提出了URL会话请求,获取数据如下所示。如何快速从响应中查询和访问这些参数。我是编程新手,请速速向我推荐。

//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()
}

响应为:

{
"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
}

4 个答案:

答案 0 :(得分:3)

Decodable协议是在Swift 4+中解析JSON的最便捷方法

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()

注意:

在这种情况下,不需要URLRequest,也不要在Swift中使用NSMutableURLRequest

答案 1 :(得分:3)

您将获得一个带有键的JSON对象:

  1. totalHits
  2. 点击次数
  3. 总计

在上述三个键中,https的值是另一个内部有许多json对象的JSON数组。你可以通过

      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
                    }

                }

这里的标签是一个字符串,由许多用逗号分隔的单词组成。 因此,您可以从 tags 字符串中获取标记数组

let tagArray = tags.components(separatedBy: ", ")

答案 2 :(得分:0)

现在您在字典中有答复,您可以执行以下操作来获得hits

guard let results = respDict as? [String: Any],
    let hits = results["hits"] as? Array<[String:Any]> else { 
    return 
}

现在,当您点击时,让我们将该对象数组转换为两个数组。网址数组和标记数组。

let urls = hits.flatMap { $0["webformatURL"] as? String }
let tags = hits.flatMap { $0["tags"] as? String }

你去了!

答案 3 :(得分:0)

这是简单的方法,

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)")
    }
}