Saving

suggest change

URLRequest takes a URL, and suggestedFilename is optional.

let url = URL(string: "https://path-to-media")!
let request = URLRequest(url: url)
let downloadTask = URLSession.shared.downloadTask(with: request) { location, response, error in
  guard let location = location,
        let filename = response?.suggestedFilename,
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else {
    return
  }
  let documentsDirectoryUrl = URL(fileURLWithPath: documentsPath)
  let documentUrl = documentsDirectoryUrl.appendingPathComponent(filename)
  try? FileManager.default.moveItem(at: location, to: documentUrl)

  // documentUrl is the local file that was just saved.
}
downloadTask.resume()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents