title: Delete files in iOS directory using Swift
body: <p>I downloaded some PDF files in my app and want to delete these on closing the application.</p>
  
  <p>For some reason it does not work:</p>
  
  <p>Creating the file:</p>
  
  <pre><code>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")
          }
      }
  }
  </code></pre>
  
  <p>Then I want to call the <code>test()</code> function to remove the items, like this:</p>
  
  <pre><code>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)")
      }
  }
  </code></pre>