Yes, you can certainly do this. After you've read the remote JSON
, it will be a Data
object.1
Build a URL
to a path in your app's caches
directory and then use the Data
method write(to:options:)
to write that data into your file.
On read, check to see if the file exists in the caches
directory before triggering a network read. Note that you need to be sure that the filenames you use are consistent and unique. (The same filename must always fetch the same unique data.)
1 Note that Mohammad has a good point. There are better ways of persisting your data than saving the raw JSON. Core Data is a pretty complex framework with a steep learning curve, but there are other options as well. You might look at conforming to the Codable protocol, which would let you serialize/deserialize your data objects in a variety of formats including JSON, property lists, and (shudder) XML.