-7

I am able to capture my data through GET method. But I wanted to display my data in a label

if let data = data, let dataString = String(data: data, encoding: .utf8) {

      print("data: \(dataString)")
}

dataString displays

data: {"data":{"id":1,"user_id":1,"month":9,"date":"2019-09-09 10:48:50","time_in":"09:00:00","time_out":"18:00:00","attendance":"\u25cf","reason":null,"estimated_time":null,"created_at":"2019-08-30 09:56:31","updated_at":"2019-09-09 10:49:48","deleted_at":null}}

I wanted to get the value of "time_in" and "time_out" and display both in a label

Olufsen
  • 160
  • 2
  • 15
  • 6
    You need to parse the JSON data, not convert it to a String. There are countless tutorials and examples on parsing JSON in Swift. Please give it a try and update your question with your attempt to parse the JSON and extract the values you need. – rmaddy Sep 09 '19 at 04:00
  • The data that you're getting is `JSON`. You shouldn't convert it to String. – Shamas S Sep 09 '19 at 04:00

1 Answers1

2

Try using Codable to parse the JSON response.

Create the models like,

struct Root: Decodable {
    let data: Response
}

struct Response: Decodable {
    let timeIn: String
    let timeOut: String
}

Now parse your JSON data like,

if let data = data {
    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let response = try decoder.decode(Root.self, from: data)
        print(response)
    } catch {
        print(error)
    }
}

Get the timeIn and timeOut values using response like,

let timeIn = response.data.timeIn
let timeOut = response.data.timeOut

You can use these timeIn and timeOut values inside your label's text.

PGDev
  • 23,751
  • 6
  • 34
  • 88
  • 1
    Thanks. I got it working now I just missed out the part about Decodable – Olufsen Sep 09 '19 at 09:41
  • Why do I get an error when I change the String to Int? I have responses in Int. I kept getting 'ketNotFound' error – Olufsen Sep 10 '19 at 09:42
  • The JSON response you gave is String. Add the JSON response that you're getting. – PGDev Sep 10 '19 at 09:50
  • I have an additional `int` in the JSON response named employee ID, i added it on the struct as `let empID: Int` but returns an error that says `keyNotFound(CodingKeys(stringValue: "emp_no", intValue: nil)` – Olufsen Sep 11 '19 at 01:24
  • There is nothing like empID or emp_no in the JSON response you added. Kindly update the JSON so I can tell you the actual reason. – PGDev Sep 11 '19 at 05:36
  • I meant `"user_id":1`... its user_id. My mistake – Olufsen Sep 11 '19 at 07:25
  • user_id is also giving you the issue? Or is it resolved now? – PGDev Sep 11 '19 at 08:03
  • Still the same issue... but only just with `int` String works as fine but the json response isnt in String so its not working – Olufsen Sep 11 '19 at 08:19