Swift 4 http get and iterate the JSON response

0

Hello, I'm learning Swift and I'm doing a GET request via URL that returns me a JSON with this structure.

{
 "data": {
 "response": [
 "https://s3.amazonaws.com/meusite/minhapasta/banners/banner-01.png",
 "https://s3.amazonaws.com/meusite/minhapasta/banners/banner-02.png",
 "https://s3.amazonaws.com/meusite/minhapasta/banners/banner-03.png"
 ]
 }
 }

.

In the Playground I'm doing this to request JSON

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

// Seta a URL
let url = URL(string: "https://adm.meusite.com.br/api/app/v1/1/usuarios/banners")!
    // faz a requisição retornando data, response, error
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    //checa se tem erro
    guard error == nil else {
        // Exibe o erro
        print(error?.localizedDescription ?? "")
        // encerra e não executa o restante do código
        return
    }
    // Remove do optional
    if  let data = data,
        // pega o conteudo do JSON converte para string
        let contents = String(data: data, encoding: String.Encoding.utf8) {
        // Printa o JSON como String
        print(contents)

    }

 }
// Encerra a requisição
task.resume()

I would like to know how to iterate this JSON, replacing this excerpt with the iteration of dictionary:

// pega o conteudo do JSON converte para string
let contents = String(data: data, encoding: String.Encoding.utf8) {
        // Printa o JSON como String
        print(contents)

    }
    
asked by anonymous 10.12.2017 / 17:21

1 answer

0

You can use a JSONSerialization method called jsonObject(with: Data) that converts the data returned by the API into an Any object. Then you need to cast from type Any to dictionary [String:Any] and access the elements also making subsequent casts of Any pro type corresponding:

do {
    if let jsonObject = (try JSONSerialization.jsonObject(with: data)) as? [String: Any],
        let dictionary = jsonObject["data"] as? [String: Any],
        let response = (dictionary["response"] as? [String])?.flatMap({URL(string: $0)}) {
        print(response)  // "[https://s3.amazonaws.com/meusite/minhapasta/banners/banner-01.png, https://s3.amazonaws.com/meusite/minhapasta/banners/banner-02.png, https://s3.amazonaws.com/meusite/minhapasta/banners/banner-03.png]\n"
        for url in response {
            print(url)
        }
    }
} catch {
    print(error)
}

Another option you have if you are using Xcode 9.x

11.12.2017 / 03:01