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

时间:2023-02-14 15:42:48

Hi I have the following code to delete a file from the files directory as a function. But it seems to work a few times when single filename string is passed but when I use it as a function and pass filenames, its not working. The code is as follows. Im using Xcode 9.2 with Swift 4.1

您好我有以下代码从文件目录中删除文件作为一个函数。但是当传递单个文件名字符串时似乎工作了几次,但是当我将它用作函数并传递文件名时,它无效。代码如下。我使用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 个解决方案

#1


0  

you need to create file path by appending filename to base url for your directory

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

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
}

#1


0  

you need to create file path by appending filename to base url for your directory

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

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
}