苹果声明NSSearchPathForDirectoriesInDomains(_:_:_:)
:
您应该考虑使用FileManager
方法urls(for:in:)
以及url(for:in:appropriateFor:create:)
哪些方法返回URL,这是首选格式。
对于Swift 5,FileManager
有一种称为的方法contentsOfDirectory(at:includingPropertiesForKeys:options:)
。contentsOfDirectory(at:includingPropertiesForKeys:options:)
具有以下声明:
对指定目录执行浅层搜索,并返回包含项的URL。
func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]
因此,为了检索documents目录中包含的文件的url,可以使用下面的代码片段: FileManager
的urls(for:in:)
和contentsOfDirectory(at:includingPropertiesForKeys:options:)
方法的:
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents)
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
例如,以下UIViewController
实现显示了如何将应用程序捆绑包中的文件保存到文档目录,以及如何获取保存在文档目录中的文件的网址:
import UIKit
class ViewController: UIViewController {
@IBAction func copyFile(_ sender: UIButton) {
// Get file url
guard let fileUrl = Bundle.main.url(forResource: "Movie", withExtension: "mov") else { return }
// Create a destination url in document directory for file
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let documentDirectoryFileUrl = documentsDirectory.appendingPathComponent("Movie.mov")
// Copy file to document directory
if !FileManager.default.fileExists(atPath: documentDirectoryFileUrl.path) {
do {
try FileManager.default.copyItem(at: fileUrl, to: documentDirectoryFileUrl)
print("Copy item succeeded")
} catch {
print("Could not copy file: \(error)")
}
}
}
@IBAction func displayUrls(_ sender: UIButton) {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents) // may print [] or [file:///private/var/mobile/Containers/Data/Application/.../Documents/Movie.mov]
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
}
}