简体   繁体   English

如何阅读和打开iOS应用程序文档目录中的文件?

[英]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. 我已经将文件夹复制到documents目录中,并且能够枚举目录的内容,但是当我检查枚举的URL是否存在并且可读时,我得到了错误。 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. absoluteString是错误的API。 You have to get paths in the file system with the path property. 您必须使用path属性在文件系统中获取路径。

And for consistency please name the URL as fileURL 为了保持一致,请将该URL命名为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)
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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