rawbee
rawbee

Reputation: 3008

How do I read and open files in an iOS app's documents directory?

I've copied a folder into the documents directory, and I'm able to enumerate the directory's contents, but when I check if the enumerated URL exists and is readable, I get false. How do I read and use these files?

let imagesURL = copyPath.appendingPathComponent("images", isDirectory: true)
guard let fileEnumerator = FileManager.default.enumerator(at: imagesURL, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions()) else { return }
while let file = fileEnumerator.nextObject() {
    guard let filepath = file as? NSURL else { continue }
    print(filepath.absoluteString!)
    let isReadable = FileManager.default.isReadableFile(atPath: filepath.absoluteString!)
    let exists = FileManager.default.fileExists(atPath: filepath.absoluteString!)
    print("isReadable: \(isReadable), exists: \(exists)")
}

Upvotes: 0

Views: 740

Answers (1)

vadian
vadian

Reputation: 285240

absoluteString is the wrong API. You have to get paths in the file system with the path property.

And for consistency please name the URL as fileURL

...
guard let fileURL = file as? URL else { continue }
print(fileURL.path)
let isReadable = FileManager.default.isReadableFile(atPath: fileURL.path)
let exists = FileManager.default.fileExists(atPath: fileURL.path)
...

Upvotes: 1

Related Questions