简体   繁体   中英

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)")
}

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)
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM