Home > database >  App Specific Directory to store files in iOS
App Specific Directory to store files in iOS

Time:10-01

I am quite new to iOS and have been learning iOS on my own from articles in the internet. But having a little bit doubts regarding downloading and saving files in iOS.

Coming from Android background, in android we can download app specific files under Android/data/com.package.name/file1. So I am trying to do the same saving files in iOS in the app specific directory. Also as like as Android would like to delete the files when the app is uninstalled. So can anyone please help me regarding this what is the correct directory in iOS to store app specific files as like as Android and how to do it. Also can user access the files in the app specific directory directly or we will need to use encryption to secure it?

CodePudding user response:

In iOS, Apple limits apps to a very limited set of "sandboxed" directories (directories that the system provides for your app.)

You can get access to a downloads directory, a documents directory, and a caches directiory.

A quick Google search found this link documenting how to get to those directories.

Lifting that (very common) code from the linked site: (Not my code, just including it for reference.)

extension UIViewController {
  
  // Get user's documents directory path
  func getDocumentDirectoryPath() -> URL {
    let arrayPaths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let docDirectoryPath = arrayPaths[0]
    return docDirectoryPath
  }
  
  // Get user's cache directory path
  func getCacheDirectoryPath() -> URL {
    let arrayPaths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
    let cacheDirectoryPath = arrayPaths[0]
    return cacheDirectoryPath
  }
  
  // Get user's temp directory path
  func getTempDirectoryPath() -> URL {
    let tempDirectoryPath = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
    return tempDirectoryPath
  }
  
}

The author of that post made it an extension of UIViewController, which means that all instances of UIViewController gain access to those properties. I'd probably make them global variables so I could have access them anywhere (or static properties of a utilities class.)

Attempting to read or write to any directory other than one of those will fail. (There is also an interface for giving the user access to a shared documents directory, and to iCloud file sharing, but that's outside the scope of this question)

  • Related