Home > database >  How to use folders in swift not visible to users?
How to use folders in swift not visible to users?

Time:07-16

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 ?

CodePudding user response:

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