0

My app receives a Json file, i need to store this json for reading this and next I've read i need to remove that. How I can storage this file in safety mode? I don't want use a "normal folder" like download, but i want to use a internal folder in my app, is possible ? And if is not possible to use my internal folder, how i can storage my file in safaty mode on ios ?

  • I would add that the preferred place should be cache directory (.cachesDirectory) . Document directory is for app document and may sometime be accessible to user and cache may be cleaned by system [see here](https://stackoverflow.com/questions/54746421/does-ios-clean-cache-directory-automatically) – Ptit Xav Jul 16 '22 at 07:09

1 Answers1

0

Well the most popular option to save a file in iOS is saving in document directory of the application.

A document directory is a directory where you can save all possible files and folders what you want, and the files are completely safe from other applications, meaning, iOS doesn't permit any application to write in other's document directory. Moreover, users won't find the directory as like android.

To save a file in the document directory, for example an image file

let fileManager = FileManager.default
do {
    let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
    let fileURL = documentDirectory.appendingPathComponent(name)
    let image = #imageLiteral(resourceName: "Notifications")
    if let imageData = image.jpegData(compressionQuality: 0.5) {
        try imageData.write(to: fileURL)
        return true
    }
} catch {
    print(error)
}

to remove the file from document directory

let fileManager = FileManager.default
    do {
        let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let fileURLs = try fileManager.contentsOfDirectory(at: documentDirectoryURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
        for url in fileURLs {
           try fileManager.removeItem(at: url)
        }
    } catch {
        print(error)
    }
Ankur Lahiry
  • 2,253
  • 1
  • 15
  • 25
  • Thank you so much, I try in these days this solution – Emanuele Mele Jul 16 '22 at 10:07
  • i don't understood what is variable "name" in appendinPath, ed you save an Image with #imageLiteal, but if i want to save an json ? – Emanuele Mele Jul 16 '22 at 10:13
  • name is just a name - like "photo", "image", the name as you want file to be saved. – Ankur Lahiry Jul 16 '22 at 16:09
  • Basically json is a file, or whatever. First you have to decode the JSON using `Codable`, then convert the object as `Data`, and then write the data (here as imageData, which is also a `Data`) to the file. But the question is basically saving the file and those questions are out of scope here. you may find thousands of examples on those in SO – Ankur Lahiry Jul 16 '22 at 16:13