Download File Using Alamofire 4.0 (Swift 3)

56,927

Solution 1

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:

Solution 2

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)")
            }
        }

Solution 3

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)
    }
}

Solution 4

Downloading mp3 file with Alamofire 4.0 Swift 4.x

Since almost all samples seems to be about downloading an image or a JSON file, it took me hours to find the right solution.
I will share it here hoping it would help others to save some time.

func startDownload(audioUrl:String) -> Void {
    let fileUrl = self.getSaveFileUrl(fileName: audioUrl)
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        return (fileUrl, [.removePreviousFile, .createIntermediateDirectories])
    }

    Alamofire.download(audioUrl, to:destination)
        .downloadProgress { (progress) in
            self.progressLabel.text = (String)(progress.fractionCompleted)
        }
        .responseData { (data) in
            self.progressLabel.text = "Completed!"
    }
}

func getSaveFileUrl(fileName: String) -> URL {
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let nameUrl = URL(string: fileName)
    let fileURL = documentsURL.appendingPathComponent((nameUrl?.lastPathComponent)!)
    NSLog(fileURL.absoluteString)
    return fileURL;
}

Solution 5

For the latest versions this is how it should look like:

let destination: DownloadRequest.Destination = { _, _ in
        let documentsURL = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("image.png")

            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
    }

    AF.download("https://httpbin.org/image/png", to: destination).response { response in
        debugPrint(response)

        if response.error == nil, let imagePath = response.fileURL?.path {
            let image = UIImage(contentsOfFile: imagePath)
        }
    }
Share:
56,927
JayVDiyk
Author by

JayVDiyk

Updated on June 01, 2020

Comments

  • JayVDiyk
    JayVDiyk almost 4 years

    In older version of Alamofire. This is how I download file

        let destinationPath = Alamofire.Request.suggestedDownloadDestination( directory: .documentDirectory, domain: .userDomainMask);
    
        Alamofire.download(.GET, urlString, destination: destinationPath)
            .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
    //                print(totalBytesRead)
            }
            .response { request, response, _, error in
    
                let downloadedFilePath = destinationPath(URL(string: "")!, response!);
    
                NSUserDefaultsHelper.saveURL(downloadedFilePath, key: urlString);
    
                completion(downloadedFilePath, true);
        }
    

    But now in the new version, my code is completely unusable and there is no similar function in the Alamofire library.

    Any ideas please?

  • JayVDiyk
    JayVDiyk over 7 years
    The code block inside the response is DefaultDownloadResponse, I am having problem in getting the final 'downloadedFilePath'
  • pedrouan
    pedrouan over 7 years
    The actual downloaded file path is destination + nameOfTheFile, isn't it?
  • JayVDiyk
    JayVDiyk over 7 years
    yes, but if you look at my code, the file name is generated automatically by Alamofire. That is why I used the destinationPath function to get the full path.
  • pedrouan
    pedrouan over 7 years
    I may misunderstood. An answer updated. Is this what you are looking for?
  • Dumitru Rogojinaru
    Dumitru Rogojinaru over 7 years
    i am sorry, but I am now in programming, I have downloaded an audio file, how do I get the url Path where it's saved correctly, in order to play the sound? thanks
  • ami rt
    ami rt almost 7 years
    why you use documentsURL, [.removePreviousFile]
  • Praburaj
    Praburaj over 6 years
    Can anyone tell how to open the file using the destination url after the file has been downloaded..
  • Gene Z. Ragan
    Gene Z. Ragan over 5 years
    DefaultDownloadResponse.destinationURL contains the url to the downloaded data
  • Monish
    Monish over 5 years
    how can i get parameters in completionHandler ?
  • famfamfam
    famfamfam over 5 years
    Hi. I downloaded success but can not find where is my video, can u help?
  • Pankaj Jangid
    Pankaj Jangid over 5 years
    @famfamfam you can find the file in document directory
  • famfamfam
    famfamfam over 5 years
    Hi. here is my file url : 'file:///Users/thehe/Library/Developer/CoreSimulator/Devices‌​/01F3C177-1B6A-4CB4-‌​AABE-45EB0D57A3C1/da‌​ta/Containers/Data/A‌​pplication/DEA4544E-‌​54A9-4104-9A7A-CAF5B‌​9D172B3/Documents/Ci‌​viX_HistoryVideo_19-‌​1-2019_7h59m28s.mp4' , then my error i got is 'The file “CiviX_HistoryVideo_19-1-2019_7h59m28s.mp4” couldn’t be saved in the folder “Documents”.'
  • Pankaj Jangid
    Pankaj Jangid over 5 years
    @famfamfam please check progress rate, If it is 100% then It will be saved into document directory