获取文档文件夹中的文件列表
我的代码在文档文件夹中获取文件名有什么问题?
func listFilesFromDocumentsFolder() -> [NSString]?{ var theError = NSErrorPointer() let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] if dirs != nil { let dir = dirs![0] as NSString let fileList = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir, error: theError) as [NSString] return fileList }else{ return nil } }
我以为我正确地阅读文件,我很确定什么是在文件夹,但“fileList”不显示任何东西? “dir”显示文件夹的path。
Xcode 8.1•Swift 3.0.1
// Get the document directory url let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! do { // Get the directory contents urls (including subfolders urls) let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: []) print(directoryContents) // if you want to filter the directory contents you can do like this: let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" } print("mp3 urls:",mp3Files) let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent } print("mp3 list:", mp3FileNames) } catch { print(error.localizedDescription) }
SWIFT 3的更短的语法
func listFilesFromDocumentsFolder() -> [String]? { let fileMngr = FileManager.default; // Full path to documents directory let docs = fileMngr.urls(for: .documentDirectory, in: .userDomainMask)[0].path // List all contents of directory and return as [String] OR nil if failed return try? fileMngr.contentsOfDirectory(atPath:docs) }
用法示例:
override func viewDidLoad() { print(listFilesFromDocumentsFolder()) }
在iOS 10.2和iPad上使用xCode 8.2.3进行testing
Swift 2.0兼容性
func listWithFilter () { let fileManager = NSFileManager.defaultManager() // We need just to get the documents folder url let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL do { // if you want to filter the directory contents you can do like this: if let directoryUrls = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants) { print(directoryUrls) ........ } } }
要么
func listFiles() -> [String] { var theError = NSErrorPointer() let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] if dirs != nil { let dir = dirs![0] do { let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir) return fileList as [String] }catch { } }else{ let fileList = [""] return fileList } let fileList = [""] return fileList }
此代码打印出我的文档目录中的所有目录和文件:
你的function的一些修改:
func listFilesFromDocumentsFolder() -> [String] { var theError = NSErrorPointer() let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] if dirs != nil { let dir = dirs![0] let fileList = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir, error: theError) return fileList as! [String] // edit: added ! for Swift 1.2 compatibitily }else{ let fileList = [""] return fileList } }
哪些被调用:
let fileManager:NSFileManager = NSFileManager.defaultManager() var fileList = listFilesFromDocumentsFolder() let count = fileList.count var isDir:Bool = true; for var i:Int = 0; i < count; i++ { if fileManager.fileExistsAtPath(fileList[i]) != true { println("File is \(fileList[i])") } }
苹果声明NSSearchPathForDirectoriesInDomains(_:_:_:)
:
您应该考虑使用
FileManager
方法urls(for:in:)
和url(for:in:appropriateFor:create:)
来返回URL,这是首选的格式。
使用Swift 3, FileManager
有一个名为contentsOfDirectory(at:includingPropertiesForKeys:options:)
的方法contentsOfDirectory(at:includingPropertiesForKeys:options:)
FileManager
contentsOfDirectory(at:includingPropertiesForKeys:options:)
。 contentsOfDirectory(at:includingPropertiesForKeys:options:)
具有以下声明:
对指定的目录执行浅层search,并返回所包含项目的URL。
func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]
因此,为了检索文档目录中包含的文件的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
实现展示了如何将应用程序包中的文件保存到文档目录以及如何获取文档目录中保存的文件的URL:
import UIKit class ViewController: UIViewController { @IBAction func copyFile(_ sender: UIButton) { // Get app bundle file url guard let bundleFileUrl = 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 bundle file to document directory if !FileManager.default.fileExists(atPath: documentDirectoryFileUrl.path) { do { try FileManager.default.copyItem(at: bundleFileUrl, to: documentDirectoryFileUrl) } 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)") } } }