I am trying to get the data from this API - (api.solunar.org/solunar/42.66,-84.07,20180207,-4). I found this tutorial (youtube.com/watch?v=gfOhBmU2cPM), but it is for a list of objects JSON API, whereas mine is just 1 single object... Does anyone know how to edit the code from the video to work with my API?
Sorry, I have been missing your words my old code the gets a multi-object array.I need to edit it to be for a single object.
But you just need to pass the struct type to decode(_:from:) instead of Array type:
For example:
Code Block struct SingleObject: Codable { var sunRise: String //... } enum ApiError: Error { case dataIsNil } class ApiCall { func getSingleObject(completion:@escaping (Result<SingleObject, Error>) -> ()) { guard let url = URL(string: "...") else { return } URLSession.shared.dataTask(with: url) { (data, _, error) in if let error = error { print(error) completion(.failure(error)) return } guard let data = data else { print("data is nil") completion(.failure(ApiError.dataIsNil)) return } do { let singleObject = try JSONDecoder().decode(SingleObject.self, from: data) //<- print(singleObject) DispatchQueue.main.async { completion(.success(singleObject)) } } catch { print(error) completion(.failure(error)) } } .resume() } }