Learn Courses My Dashboard

Printing data on a label using JSONEnconder

Hi community,

I have data saved from a different view controller and I’m trying to print the result using my label on another view controller.

The app requires 3 inputs:

To test if I’m getting the data, I’m using JSONEncoder

func getSchedule(){
        
        if let data = UserDefaults.standard.data(forKey: "sched recording") {
            do {
                // Create JSON Decoder
                let decoder = JSONDecoder()

                // Decode Note
                let scheduleRecording = try decoder.decode(ScheduleRecording.self, from: data)
                print("Recording info: \(scheduleRecording)")
                
            } catch {
                print("Unable to Decode Schedule Recording (\(error))")
                print("No Schedule Recording")
            }
    }
        else{
            print("No Schedule Recording")
        }
    }

and the output on the console looks like this:

Recording info ScheduleRecording(startTime: 2022-08-15 17:00:00 +0000, endTime: 2022-08-15 05:00:00 +0000, repeatNum: 1)

Tried printing data on my label:

Now, I want to print the result on the app a bit neater. E.g.,

Start Time: x
End Time: y
Repeat: i

Is it possible to split the data I get from the decoder to do this?

Use the properties of your object Right now you are filling the entire object into the label with string interpolation. Do the same thing, but access each property

label.text = “\(scheduleRecording.startTime) \n \(scheduleRecording.endTime) \n \(scheduleRecording.repeatNum)”

Also note \n means linebreak

Worked for me! Thanks Mikaela :slight_smile: