-2

Is there any way I can download json file from webserver and store it in a local folder for easy access for those with poor internet connection, so data will be downloaded once and user won't have to suffer every time.

I found similar questions on here1 and here2, but they were asked for objective-C, but I was looking something for Swift. Thanks

Curtis
  • 1,157
  • 4
  • 17
  • 30
  • there are better ways for persistent data. you can use Coredata or realm for data persistent. – Mohammadalijf Jan 28 '18 at 12:10
  • I need to find a quick resolution to store data locally, as a long term solution I will later look into CoreData but not now, thanks for suggestions though – Curtis Jan 28 '18 at 13:31

2 Answers2

1

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.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

Yes, you can create a .json file and store it in documents folder. First see how to create .json file, and then see how to store a file in documents folder.

Check this

Darko
  • 615
  • 7
  • 21
  • It’s the same link given in the question, it’s objective-c – Curtis Jan 28 '18 at 13:29
  • The one answer I linked most definitely isn't objective c. – Darko Jan 28 '18 at 14:34
  • For something like this that can be recovered from the remote server easily, the caches folder is a better choice than the Documents folder. Apple wants you to only use the Documents folder for user content that can't be easily re-aquired. – Duncan C Jan 28 '18 at 15:17