0

Im calling this api to receive single rocket launch event: https://launchlibrary.net/1.4/launch/next/1 using simple Get request. Trying to decode using SwiftyJson (also tried Codable) with lack of success to read the "rocket" -> "imageURL"

here is my code:

struct LaunchHistory {
var launches = [LaunchItem]()

init(with json:JSON) {
    for launch in json["launches"].arrayValue {
        let launchItem = LaunchItem(with: launch)
        launches.append(launchItem)
     }
   }
 }


struct LaunchItem {
let id:Int?
let name: String?
let tbddate: Int?
let status: LaunchStatus?
let rocketImage: String?

init(with json:JSON) {
    self.id = json["id"].int
    self.name = json["name"].string
    self.tbddate = json["tbddate"].int
    self.status = LaunchStatus(rawValue: json["status"].int ?? 0)
    self.rocketImage = json["rocket"]["imageURL"].string
    }
}

when LaunchItem decoded, all i 11 properties/key instead of almost double. the rocket object is missing. what am i missing here?

thanks!

1

1 Answer 1

1

It's pretty easy with (De)Codable

struct Root : Decodable {
    let launches : [LaunchItem]
}

struct LaunchItem : Decodable {
    let id: Int
    let name: String
    let tbddate: Int
    let rocket: Rocket
}

struct Rocket : Decodable {
    let imageURL : URL
}

let url = URL(string: "https://launchlibrary.net/1.4/launch/next/1")!
let task = URLSession.shared.dataTask(with: url) { (data, _, error) in
    if let error = error { print(error); return }
    do {
        let result = try JSONDecoder().decode(Root.self, from: data!)
        print(result.launches.first?.rocket.imageURL ?? "n/a")
    } catch {
        print(error)
    }

}
task.resume()
Sign up to request clarification or add additional context in comments.

1 Comment

look pretty much as i did (the codable part which i not added), but it works :) thanks for the help. ill try to look into the diffrences

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.