简体   繁体   中英

Saving a file with a variable of datatype 'Data" in Swift

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

  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) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM