如何读取和打开 iOS 应用的文档目录中的文件?
How do I read and open files in an iOS app's documents directory?
我已经将一个文件夹复制到文档目录中,并且能够枚举该目录的内容,但是当我检查枚举的 URL 是否存在且可读时,我得到了错误。如何阅读和使用这些文件?
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
是错误的API。您必须使用 path
属性.
获取文件系统中的路径
为了保持一致性,请将 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)
...
我已经将一个文件夹复制到文档目录中,并且能够枚举该目录的内容,但是当我检查枚举的 URL 是否存在且可读时,我得到了错误。如何阅读和使用这些文件?
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
是错误的API。您必须使用 path
属性.
为了保持一致性,请将 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)
...