【问题标题】:How to check if multiple files exist in documents directory? (Swift)如何检查文档目录中是否存在多个文件? (迅速)
【发布时间】:2018-07-15 13:56:25
【问题描述】:

我可以用这个方法检查一个文件是否存在:

let fileNameOne = "savedpicture1"
let fileURLOne = documentsDirectoryURL.appendingPathComponent(fileNameOne) 

if !FileManager.default.fileExists(atPath: fileURLOne.path) {
       removeImage(itemName: "savedpicture1", fileExtension: "jpg")
 } else {
        print("There was no image to remove")
 }

我的问题是必须为多个文件重复相同的代码行。例如,我想检查文件是否存在于路径数组中,但我必须为每个文件重复上面的代码,这似乎太多余了。我想知道是否有一种方法可以检查多个文件,而不是为每个路径重复代码。 ".fileExists" 只能让我检查一个路径:

 let filePaths = [fileURLOne.path, fileURLTwo.path, fileURLThree.path, 
 fileURLFour.path] 

【问题讨论】:

    标签: swift nsfilemanager nsdocumentdirectory


    【解决方案1】:

    例如写一个方法

    func checkFiles(with fileNames: [String] {
        for fileName in fileNames {
            let fileURL = documentsDirectoryURL.appendingPathComponent(fileName) 
            if !FileManager.default.fileExists(atPath: fileURL.path) {
                removeImage(itemName: fileName, fileExtension: "jpg")
            } else {
                print("There was no image to remove at", fileURL)
            }
        }
    }
    

    并称之为

    let fileNames = ["savedpicture1", "savedpicture2", "savedpicture3",  "savedpicture4"] 
    checkFiles(with: fileNames)
    

    【讨论】:

    • 非常感谢,这正是我想要的。
    猜你喜欢
    • 2011-09-23
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2012-07-02
    • 2014-03-06
    • 1970-01-01
    相关资源
    最近更新 更多