Creating a folder in Application Support

In a sandboxed document based project for macOS, I would like to programmatically save on disk a document. The location have to be not accessible to the users: I would have thought of "CurrentFiles" or such, into Application Support folder. How can I create the folder?


This is the code I 'M using to date for testing:


let directoryURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first // then use .applicationSupportDirectory
      
        let docURL = URL(string:"MyFile.test", relativeTo:directoryURL)
      
        if (try? document.write(to: docURL!, ofType: "com.myCompany.test")) != nil {
        } else {
            print("An error occured")
        }

Accepted Reply

You'll need to use a file URL. Try something like this:


do
{
  //  Find Application Support directory
  let fileManager = FileManager.default
  let appSupportURL = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
  //  Create subdirectory
  let directoryURL = appSupportURL.appendingPathComponent("com.myCompany.myApp")
  try fileManager.createDirectory (at: directoryURL, withIntermediateDirectories: true, attributes: nil)
 //  Create document
  let documentURL = directoryURL.appendingPathComponent ("MyFile.test")
  try document.write (to: documentURL, ofType: "com.myCompany.test")
}
catch
{
  print("An error occured")
}

Replies

You'll need to use a file URL. Try something like this:


do
{
  //  Find Application Support directory
  let fileManager = FileManager.default
  let appSupportURL = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
  //  Create subdirectory
  let directoryURL = appSupportURL.appendingPathComponent("com.myCompany.myApp")
  try fileManager.createDirectory (at: directoryURL, withIntermediateDirectories: true, attributes: nil)
 //  Create document
  let documentURL = directoryURL.appendingPathComponent ("MyFile.test")
  try document.write (to: documentURL, ofType: "com.myCompany.test")
}
catch
{
  print("An error occured")
}

Thank you QuinceyMorris, and if I wanted to create these files in a subfolder "MyDcuments" instead of create it directly in "com.myCompany.myApp", how would I do it?


Application Support/com.myCompany.myApp/myDocuments/

You can just add a component to the directory URL:


  let directoryURL = appSupportURL.appendingPathComponent("com.myCompany.myApp").appendingPathComponent("myDocuments")

Thanks, you made me understand something I did not understand by reading docs.