title: How to download and save an audio file and then play it in swift?
body: <p>I am trying to download an audio file from the internet and save it onto the phone. This is the download function:</p>
  
  <pre><code>func download() {
      if let audioUrl = downloadUrl {
  
          // then lets create your document folder url
          let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
  
          // lets create your destination file url
          let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
          print(destinationUrl)
  
          // to check if it exists before downloading it
          if FileManager.default.fileExists(atPath: destinationUrl.path) {
              print("The file already exists at path")
  
              // if the file doesn't exist
          } else {
  
              // you can use NSURLSession.sharedSession to download the data asynchronously
              URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -&gt; Void in
                  guard let location = location, error == nil else { return }
                  do {
                      // after downloading your file you need to move it to your destination url
                      try FileManager.default.moveItem(at: location, to: destinationUrl)
                      print("File moved to documents folder")
                  } catch let error as NSError {
                      print(error.localizedDescription)
                  }
              }).resume()
          }
      }
  }
  </code></pre>
  
  <p>Then, after I close and open the app, I use the following function to retrieve the url and play it using an AVPlayer:</p>
  
  <pre><code>func getUrl2() {
      if let audioUrl = downloadUrl {
  
          // then lets create your document folder url
          let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
  
          destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
  
          if let u = self.destinationUrl {
              let player = AVPlayer(url: u)
              print(u)
              print("Bouta play")
              print(CMTimeGetSeconds(player.currentItem!.duration))
              player.play()
          }
      }
  }
  </code></pre>
  
  <p>The duration that keeps getting printed out is "nan". Is there a way to check if the audio file is actually downloading? Or could it be a problem with retrieving the file after the download? Thanks in advance.</p>