Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete files in iOS directory using Swift

Tags:

ios

swift

I downloaded some PDF files in my app and want to delete these on closing the application.

For some reason it does not work:

Creating the file:

let reference = "test.pdf"     let RequestURL = "http://xx/_PROJEKTE/xx\(self.reference)" let ChartURL = NSURL(string: RequestURL)  //download file let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL let destinationUrl = documentsUrl.URLByAppendingPathComponent(ChartURL!.lastPathComponent!) if NSFileManager().fileExistsAtPath(destinationUrl.path!) {     print("The file already exists at path") } else {     //  if the file doesn't exist     //  just download the data from your url     if let ChartDataFromUrl = NSData(contentsOfURL: ChartURL!){         // after downloading your data you need to save it to your destination url         if ChartDataFromUrl.writeToURL(destinationUrl, atomically: true) {             print("file saved")             print(destinationUrl)         } else {             print("error saving file")         }     } } 

Then I want to call the test() function to remove the items, like this:

func test(){      let fileManager = NSFileManager.defaultManager()     let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL      do {         let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)")         for filePath in filePaths {             try fileManager.removeItemAtPath(NSTemporaryDirectory() + filePath)         }     } catch {         print("Could not clear temp folder: \(error)")     } } 
like image 356
Fabian Boulegue Avatar asked Dec 19 '15 10:12

Fabian Boulegue


People also ask

How to remove file in iOS swift?

Creating the deleting function to delete a file in Swift First, you must create a variable for the name and extension from the input “fileToDelete” from the user. Here, “fName” is used to store the file name, and “fExtension” to store the file extension.

How do I delete files from Iphone folder?

To delete a file, select it and tap the Delete button . If you delete files from the iCloud Drive folder on one device, they are automatically deleted on your other devices, too.

How do I clear my directory?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.


2 Answers

This code works for me. I removed all the images that were cached.

private func test(){      let fileManager = NSFileManager.defaultManager()     let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! as NSURL     let documentsPath = documentsUrl.path      do {         if let documentPath = documentsPath         {             let fileNames = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")             print("all files in cache: \(fileNames)")             for fileName in fileNames {                  if (fileName.hasSuffix(".png"))                 {                     let filePathName = "\(documentPath)/\(fileName)"                     try fileManager.removeItemAtPath(filePathName)                 }             }              let files = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")             print("all files in cache after deleting images: \(files)")         }      } catch {         print("Could not clear temp folder: \(error)")     } } 

**** Update swift 3 ****

        let fileManager = FileManager.default         let documentsUrl =  FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! as NSURL         let documentsPath = documentsUrl.path          do {             if let documentPath = documentsPath             {                 let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")                 print("all files in cache: \(fileNames)")                 for fileName in fileNames {                      if (fileName.hasSuffix(".png"))                     {                         let filePathName = "\(documentPath)/\(fileName)"                         try fileManager.removeItem(atPath: filePathName)                     }                 }                  let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")                 print("all files in cache after deleting images: \(files)")             }          } catch {             print("Could not clear temp folder: \(error)")         } 
like image 95
Saleh Masum Avatar answered Oct 05 '22 23:10

Saleh Masum


I believe your problem is on this line:

let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)") 

You're using contentsOfDirectoryAtPath() with something that is an NSURL. You choose either path strings or URLs, not try to mix them both. To pre-empty your possible next question, URLs are preferred. Try using contentsOfDirectoryAtURL() and removeItemAtURL().

Another curious thing you should look at once you resolve the above: why are you using NSTemporaryDirectory() for the file path when you try to delete? You're reading the document directory and should use that.

like image 23
TwoStraws Avatar answered Oct 05 '22 23:10

TwoStraws