Home > database >  Delete file on applicationSupportDirectory - Swift 5
Delete file on applicationSupportDirectory - Swift 5

Time:12-19

How can I delete a single file from applicationSupportDirectory? This is what I'm using to create it:

func encodeFileStoredInDisk<U : Encodable>(dataToStore: U, fileName: String, fileExtension: String) throws {
    let fileURL = try FileManager.default
        .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent(fileName)
        .appendingPathExtension(fileExtension)

    try JSONEncoder().encode(dataToStore)
        .write(to: fileURL)
}

I tried this based on the docs but it's unrecognizable, which hints me it's completly wrong:

func deleteFileOnDisk(fileName: String, fileExtension: String) throws {
    let fileURL = try FileManager.default
        .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        .appendingPathComponent(fileName)
        .appendingPathExtension(fileExtension)
    
    removeItem(at URL: fileURL)
}

CodePudding user response:

Your given code already reveals how to call a method which belongs to FileManager so start with

FileManager.default.rem

Code completion will suggest

FileManager.default.removeItem(at: <#T##URL#>)

and will tell you also to mark the method with try, click on the red circle in front of the error message and choose the first Fix option

try FileManager.default.removeItem(at: fileURL)
  • Related