0

I'm new to programming and I'm trying to write a function in Swift to download a JSON and parse it. However, the JSON is very complicated and I have a daily limit on number of requests of data from the server.

Is there a way to download the data and save it to a file as 'data' so I can run all tests on this data in the file and not have to get it from the server everytime? Once I'm ready, I can start getting data from the server again.

Basically I could initialize a data variable with the contents of the file so I can use it on my tests.

Thank you

  • Yes, you can download the data and add it to your project. Then you can load it from your application bundle. – koen Apr 28 '20 at 16:20

1 Answers1

0
  1. Determine where you want to store it and what it should be named. For example, for files that can be re-retrieved from the network, we’d use the cachesDirectory:

    let folder = try! FileManager.default
        .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("downloads")
    

    Or, you can use the applicationSupportDirectory (if re-retrieving it is impractical) or .documentsDirectory (if you want to potentially expose the file to the end user). But the idea is the same.

  2. Create that folder if you haven’t already:

    try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
    
  3. Create URL for the file within that folder:

    let fileURL = folder.appendingPathComponent("sample.json")
    
  4. Save that Data to that fileURL:

    do {
        try data.write(to: fileURL)
    } catch {
        print(error)
    }
    
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • I get the following error on the line with the data.write - Cannot convert value of type 'URL' to expected argument type 'Target' -- I was getting that error earlier, but I couldn't figure out why it is happening. – Daniel Poit F Apr 28 '20 at 18:29
  • Thank you, I actually got it. I had the wrong type being passed into the function. – Daniel Poit F Apr 28 '20 at 18:50