Saving Data in iOS

May 31 2022 · Swift 5.5, iOS 15, Xcode 13

Part 2: JSON

15. Challenge: Encoding JSON Arrays

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 14. JSON Encoding Next episode: 16. Codable Hierarchies

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 15. Challenge: Encoding JSON Arrays

This course was originally recorded in April 2020. It has been reviewed and all content and materials updated as of November 2021.

Transcript: 15. Challenge: Encoding JSON Arrays

Time to save the array of prioritized tasks. Update the savePrioritizedTask method to achieve this. Additonally, try to improve the output format of the JSON in your file so it’s easier to read. Have fun and see you back in a bit!

The first thing I did was update the method signature so it reflects we are storing multiple tasks and not just one.

saveJSONPrioritizedTasks

Next up is storing the array of prioritized tasks.

let tasksData = try encoder.encode(prioritizedTasks)

Yup, it’s that simple. You simply pass it your prioritizedTasks array and you’re done. Almost! Be sure to clean up the code that writes your data to the file in order to use the new constant name as well as the URL you declared in the class right at the end of the last video.

try tasksData.write(to: tasksJSONURL, options: .atomicWrite)

Build and run your app, make sure you still have the PrioritizedTasks.json file in the Document directory, and try adding a task.

Ta daaaa! You now have an array of prioritized tasks, but the formatting is making it difficult to really make out each tasks and their details.

This is where the bonus objective comes in. You can tell JSONEncoder that you want to use a pretty format. Add this line right after creating your encoder.

encoder.outputFormatting = .prettyPrinted

If you run your app and create (or delete) a task now, you will notice the resulting file is much easier to read!