0

I’m having trouble createing a temporary directory in iOS using Swift 3. I’m getting the temporary directory URL from FileManager.temporaryDirectory, and trying to create the directory using FileManager.createDirectory, but the directory doesn’t appear to exist, and I’m not able to create files in it. What am I doing wrong?

let fileManager = FileManager.default
let tempDir = fileManager.temporaryDirectory
let tempDirString = String( describing: tempDir )
print( "tempDir: \(tempDir)" )
print( "tempDirString: \(tempDirString)" )
if fileManager.fileExists(atPath: tempDirString ) {
    print( "tempDir exists" )
} else {
    print( "tempDir DOES NOT exist" )
    do {
        try fileManager.createDirectory( at: tempDir, withIntermediateDirectories: true, attributes: nil )
        print( "tempDir created" )
        if fileManager.fileExists(atPath: tempDirString ) {
            print( "tempDir exists" )
        } else {
            print( "tempDir STILL DOES NOT exist" )
        }
    } catch {
        print( "tempDir NOT created" )
    }
}

This produces the output:

tempDir: file:///private/var/mobile/Containers/Data/Application/D28B9C5E-8289-4C1F-89D7-7E9EE162AC27/tmp/
tempDirString: file:///private/var/mobile/Containers/Data/Application/ D28B9C5E-8289-4C1F-89D7-7E9EE162AC27/tmp/
tempDir DOES NOT exist
tempDir created
tempDir STILL DOES NOT exist
Jerry Agin
  • 629
  • 1
  • 5
  • 15

1 Answers1

3

The tempDirString string you are passing to fileManager.fileExists(atPath: tempDirString ) contains a string, but the string is NOT a file path. It is a description for human readable purposes, not for machine-readable purposes. In fact, it is not even a valid URL string (notice the space in it!).

If you want the path, replace this line:

let tempDirString = String( describing: tempDir )

and instead assign to tempDirString the results of the NSURL's path function to get the path as a string:

let tempDirString = tempDir.path

See: https://developer.apple.com/reference/foundation/nsurl/1408809-path

Son of a Beach
  • 1,733
  • 1
  • 11
  • 29