Search code examples
jsonswiftjsondecoder

JSON using Swift 4


First of all, my question may have already been asked but I search on many tutorial and forums and I can't make it works because I'm french and not very good in English.

I try to read JSON with my app but It doesn't work. The only thing printed is "Foundation.JSONDecoder"

This is my SWIFT 4 code :

func getSpots(){
    guard let downloadURL = URL(string: "http://dronespot.fr/getSpot.php") else { return }
    URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
        guard let data = data, error == nil, urlResponse != nil else {
            print("Oops Call for Help")
            return
        }

        print("downloaded")
        do
        {
            let decoder = JSONDecoder()
            //let rates = try decoder.decode([Artwork].self, from: data)
            print(decoder)
        } catch {
            print("Error after loading")
        }
        }.resume()
}

Artwork.swift :

init?(json: [Any]) {
    // 1
    self.title = json[16] as? String ?? "No Title"
    self.locationName = json[12] as! String
    self.id = 3
    self.img = "tamere"
    // 2
    if let latitude = Double(json[18] as! String),
        let longitude = Double(json[19] as! String) {
        self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    } else {
        self.coordinate = CLLocationCoordinate2D()
    }
}

Expected JSON :

http://dronespot.fr/getSpot.php Thanks for your help


Solution

  • Since you want to use JSONDecoder your approach is completely wrong (apart from the issue that you commented out the actual line to decode the JSON).

    Create Artwork as a struct adopting Decodable, declare the keys in the JSON as properties and add a lazy instantiated variable to build the coordinate:

    struct Artwork : Decodable {
        let nom : String
        let description : String
        let id: String
        let img1 : String
        let latitude : String
        let longitude : String
    
        // there are much more keys
    
        lazy var coordinate : CLLocationCoordinate2D = {
            return CLLocationCoordinate2D(latitude: Double(latitude) ?? 0.0, longitude: Double(longitude) ?? 0.0)
        }()
    }
    

    Now decode the array of Artwork

    do {
        let decoder = JSONDecoder()
        let rates = try decoder.decode([Artwork].self, from: data)
        print(rates)
    } catch {
        print("Error after loading", error)
    }