Download File Using Alamofire 4.0 (Swift 3) Download File Using Alamofire 4.0 (Swift 3) ios ios

Download File Using Alamofire 4.0 (Swift 3)


I used to use this statements:

let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)Alamofire.download(    url,    method: .get,    parameters: parameters,    encoding: JSONEncoding.default,    headers: nil,    to: destination).downloadProgress(closure: { (progress) in        //progress closure    }).response(completionHandler: { (DefaultDownloadResponse) in        //here you able to access the DefaultDownloadResponse        //result closure    })

For more details read more in Alamofire docs about Migration to 4.0:


Swift 4.0

 let destination: DownloadRequest.DownloadFileDestination = { _, _ in            var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]            documentsURL.appendPathComponent("file.csv")            return (documentsURL, [.removePreviousFile])        }        Alamofire.download(url, to: destination).responseData { response in            if let destinationUrl = response.destinationURL {               print("destinationUrl \(destinationUrl.absoluteURL)")            }        }


There are several enhancements in Alamofire 4. The first of which is the optionality of the destination closure. Now, by default, the destination closure is nil which means the file is not moved anywhere on the file system and the temporary URL is returned.

This is the default execution:-

Alamofire.download(urlString).responseData { response in    print("Temporary URL: \(response.temporaryURL)")}

This is my code to download file with Alamofire 4.0 which return destination Url of file:-

let destination: DownloadRequest.DownloadFileDestination = { _, _ in        var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]        documentsURL.appendPathComponent("duck.png")        return (documentsURL, [.removePreviousFile])    }    Alamofire.download(url, to: destination).responseData { response in    if let destinationUrl = response.destinationURL ? {        completionHandler(destinationUrl)    }}