Search code examples
iosnsfilemanager

How is it possible to create directories inside your application directory in iOS?


I've tried to create a directory inside my app's directory and got the following error:

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “Some” in the folder “97391D11-283C-49FA-9A2B-8F8E2BBD89EE”." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/97391D11-283C-49FA-9A2B-8F8E2BBD89EE/Some/, NSUnderlyingError=0x2819c2df0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}: file VocalTraineriOS/VocalTrainerApp.swift, line 37

Here is my code:

try! FileManager.default.createDirectory(atPath: NSHomeDirectory() + "/Some/", withIntermediateDirectories: true)

Solution

  • You can try creating a folder inside the .documentDirectory like following.

    do {
        let fileManager = FileManager.default
        let documentsDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let someFolderURL = documentsDirectory.appendingPathComponent("Some")
        try fileManager.createDirectory(at: someFolderURL, withIntermediateDirectories: true, attributes: nil)
        print(someFolderURL)
    } catch {
        print(error)
    }
    

    Documents directory URL has this format -

    "file:///var/mobile/Containers/Data/Application/FB12D808-9054-4799-9C69-115ACD805A24/Documents/"