Networking and Persistence with JSON in Swift 4 (Part 2)
Thank you all for the great feedback on the previous article! Some of you wanted to know more about different networking requests and alternative persistence methods, so hopefully I can shed some more light on the matter with this article. If you haven’t already, I recommend reading Part 1 to learn a bit about making a simple GET request to JSONPlaceholder, converting the response data to structs, and saving those structs to disk.
Networking — making a POST request using structs
Carrying on the example from Part 1, we’ll start out with a struct representation of a Post on JSONPlaceholder’s simple REST API:
And let’s say we want to submit a Post to our cool API:
First we would need to use JSONEncoder
to encode our Codable
struct into JSON data, which we would then place in our URLRequest
’s HTTP body.
After we submit our Post…
… we should receive this response from JSONPlaceholder:
Now that you know how to make GET and POST requests, making PUT, PATCH, and DELETE requests should be a piece of cake 🍰
Cool ways to persist structs on disk
In Part 1, I briefly went over how to store Post structs onto the user’s disk using Foundation
’s built in storage helper methods. As per some of your requests, here are a few other ways of tackling the same problem.
Disk 💾
A delightful little framework I created to make persistence on iOS simple and fun, checkout it out on GitHub!
For all the other ways, we’ll be using this helper method to retrieve a URL to the user’s documents directory:
FileManager
😎
Besides Disk, this is my favorite way to handle JSON data. FileManager
gives you a lot of access to information about files anywhere you have access to, respective file permissions, etc.
NSKeyedArchiver/NSKeyedUnarchiver 👵🏻
Streams (Output and Input streams) 🤓
Instead of dealing with buffers and mutating a Data instance, we could alternatively use Apple’s JSONSerialization class which handles all this work for us. Although it can seem a bit redundant, it looks much prettier:
Conclusion
I think it’s awesome that Apple has devoted so much time and manpower to making our lives as developers easier. In the old days, persisting data structures to disks was a hassle, and with the introduction of value-type structures in Swift, working with & managing data models has never been easier or as fun. Gone are the days of reference-typed data structures 🎉🎊🎉
Networking with the provided built-in classes in Foundation
has also never been as robust and simple as it is today either. URLSession
is becoming easier to use and hunky frameworks like Alamofire & Moya are going to go obsolete before you know it.
Feel free to reach out to me on Twitter with your thoughts, or if you need any help :)