ios - 获取文档文件夹中的文件列表

标签 ios swift

我获取文档文件夹中文件名的代码有什么问题?

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”显示文件夹的路径。

最佳答案

swift 5

do {
    // Get the document directory url
    let documentDirectory = try FileManager.default.url(
        for: .documentDirectory,
        in: .userDomainMask,
        appropriateFor: nil,
        create: true
    )
    print("documentDirectory", documentDirectory.path)
    // Get the directory contents urls (including subfolders urls)
    let directoryContents = try FileManager.default.contentsOfDirectory(
        at: documentDirectory,
        includingPropertiesForKeys: nil
    )
    print("directoryContents:", directoryContents.map { $0.localizedName ?? $0.lastPathComponent })
    for url in directoryContents {
        print(url.localizedName ?? url.lastPathComponent)
    }
    
    // if you would like to hide the file extension
    for var url in directoryContents {
        url.hasHiddenExtension = true
    }
    for url in directoryContents {
        print(url.localizedName ?? url.lastPathComponent)
    }

    // if you want to get all mp3 files located at the documents directory:
    let mp3s = directoryContents.filter(\.isMP3).map { $0.localizedName ?? $0.lastPathComponent }
    print("mp3s:", mp3s)
    
} catch {
    print(error)
}

您需要将这些扩展添加到您的项目中

extension URL {
    var typeIdentifier: String? { (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier }
    var isMP3: Bool { typeIdentifier == "public.mp3" }
    var localizedName: String? { (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName }
    var hasHiddenExtension: Bool {
        get { (try? resourceValues(forKeys: [.hasHiddenExtensionKey]))?.hasHiddenExtension == true }
        set {
            var resourceValues = URLResourceValues()
            resourceValues.hasHiddenExtension = newValue
            try? setResourceValues(resourceValues)
        }
    }
}

关于ios - 获取文档文件夹中的文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27721418/

相关文章:

ios - 在应用程序和今日小部件之间共享图像资源

ios - 如何在 ios UITest 中通过其 testID 获取 React Native TextInput

ios - 如何向选定的 iPhone 用户发送推送通知?

ios - Swift 的 Spotify API

objective-c - 使用网桥从 .framework 导入文件时出错

iphone - 删除我的应用程序时调用状态更改网络服务

ios - 在执行 segue 之前如何显示加载指示器?

ios - XC文本 : query for text in navigation bar

ios - 使用 spritekit 使 Sprite 快速移动

swift - SpriteNodes 之间没有碰撞检测