从Swift 4中的Files Directory中删除用户选择的文件?

时间:2018-05-15 07:06:04

标签: ios swift file

您好我有以下代码从文件目录中删除文件作为函数。但是当传递单个文件名字符串时,它似乎工作了几次,但是当我将它用作函数并传递文件名时,它无效。 代码如下。 我使用Xcode 9.2和Swift 4.1

//USAGE
//User Clicks on a delete button and that will present an Alert Dialog with a list of files and user clicks on the file he/she would like to delete
/////////////////////////////////////////////////////
@IBAction func deleteConfigAction(_ sender: Any) {
    //---
    //---

    //Another function is called to list all files in the files directory and then store it into a string variable
    var file1: String = "Empty"

    //Calling another function to load all files present
    var userFilesPresent : [String] = listFilesPresent()!

    //For Example
    file1 = userFilesPresent[0]

    //---
    let alert = UIAlertController(title: "Delete File", message: "Select a file to be deleted", preferredStyle: UIAlertControllerStyle.alert)

    alert.addAction(UIAlertAction(title: file1, style: .default,handler: { (action: UIAlertAction!) in

        self.deleteFileSelected(fileName: file1)

        print("file deleted =",file1)

    }))

    alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.cancel, handler: nil))

    // show the alert
    self.present(alert, animated: true, completion: nil)
}

//----------------------------------------------------------------
//FUNCTION

func deleteFileSelected(fileName:String) -> [String]? {
    //Set Files directory path

    let mypath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)

    if mypath.count > 0 {

        let directoryPath = mypath[0]

        //Filter for txt files
        let searchfilePath = NSString(format:"%@/%@.txt", directoryPath, fileName) as String

        if FileManager.default.fileExists(atPath: searchfilePath) {
            do {
                //file exists, now try deleting the file
                try FileManager.default.removeItem(atPath: searchfilePath)
                print("File deleted")
            } catch {
                print("Error")
            }
        }
    }

    return nil
}

1 个答案:

答案 0 :(得分:0)

您需要通过将文件名附加到目录的基本网址来创建文件路径

func delete(fileName : String)->Bool{
    let fileManager = FileManager.default
    let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let filePath = docDir.appendingPathComponent(fileName)
    do {
        try FileManager.default.removeItem(at: filePath)
        print("File deleted")
        return true
    }
    catch {
        print("Error")
    }
    return false
}