Home > Net >  Fetch API Swift
Fetch API Swift

Time:06-10

Previously the API I was working on was as below

{
  "kurumsicilno": 457.0,
  "yillikizin": 30.0,
}

and I built my model as below

struct Leave: Decodable, Identifiable {
    var id: Double? {
        return registerNumber
    }
    let registerNumber: Double
    let annualLeave: Double
    
    enum CodingKeys: String, CodingKey {
        case registerNumber = "kurumsicilno"
        case annualLeave = "yillikizin"
    }
}

This was my network function

 let task = session.dataTask(with: request) { (data, response, error) in
            if error == nil {
                let decoder = JSONDecoder()
                if let safeData = data {
                    do {
                        let result = try decoder.decode(Leave.self, from: safeData)
                        DispatchQueue.main.async {
                            completion(result)
                        }
                    } catch {
                        print(error)
                    }
                }
            }
        }
        task.resume()

But for some reason, they have changed the API to this.

{
"isSucceed": true,
"singleData": {
    "sicilNo": "457",
    "yillikIzin": "30",
},

How should I modify my model so that I can reach and fetch the data as before?

CodePudding user response:

Just create a new root struct

struct Response : Decodable {
   let isSucceed: Bool
   let singleData: Leave
}

and you have to change the types and (one of) the CodingKeys

struct Leave: Decodable, Identifiable {
    var id: String { // no Optional!!
        return registerNumber
    }
    let registerNumber: String
    let annualLeave: String
    
    enum CodingKeys: String, CodingKey {
        case registerNumber = "sicilNo"
        case annualLeave = "yillikIzin" // is this really a capital `I`?
    }
}

Finally change the decoding code

let result = try decoder.decode(Response.self, from: safeData)
      DispatchQueue.main.async {
          completion(result.singleData)
      }

And you might have to manage the type change Double → String in your other code.

  • Related