I realise the original question is in Obj-C, but this comes up in a Google search, so for anyone else stumbling upon it and and needing the Swift version of @Lou Franco's answer, here it is:
let configuration = URLSessionConfiguration.default
let manager = AFURLSessionManager(sessionConfiguration: configuration)
let url = URL(string: "http://example.com/download.zip")! // TODO: Don't just force unwrap, handle nil case
let request = URLRequest(url: url)
let downloadTask = manager.downloadTask(
with: request,
progress: { (progress: Progress) in
print("Downloading... progress: \(String(describing: progress))")
},
destination: { (targetPath: URL, response: URLResponse) -> URL in
// TODO: Don't just force try, add a `catch` block
let documentsDirectoryURL = try! FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
return documentsDirectoryURL.appendingPathComponent(response.suggestedFilename!) // TODO: Don't just force unwrap, handle nil case
},
completionHandler: { (response: URLResponse, filePath: URL?, error: Error?) in
print("File downloaded to \(String(describing: filePath))")
}
)
downloadTask.resume()
Couple of notes here:
- This is Swift 3 / Swift 4
- I added a
progress
closure as well (just a print
statement). But of course it's totally fine to pass nil
there as in the original example.
- There are three places (marked with
TODO:
) with no error handling where things might fail. Obviously you should handle these errors, instead of just crashing.