Download PDF file using Alamofire in Swift3


Almofire is a very popular library for networking related coding(eg. API call, Downloading Stuffs etc) and totally developed in swift which is replacement of AFNetworking library of ObjectiveC. It has multiple features like Image cacheing, API call integration,File downloading etc. Today we are going to dive into Download PDF file using Alamofire in Swift.

Pods are available for almofire on GitHub for integration of this library into your own project, some steps are explained as follows:- 

  • First create a pod file for implementing the Alamofire and MBProgressHUD

pod ‘Alamofire’ // Download PDF file
pod ‘MBProgressHUD’ //Downloading Progress Bar

  • We have to create Webview Object for open downloaded PDF url.
  • Use following function in view controller and pass the url string to the function.


 func downloadPDFFile(urlString:String)


    let hud = MBProgressHUD.showAdded(to: self.view, animated: true)

    hud.mode = MBProgressHUDMode.annularDeterminate

    hud.label.text = “Loading…”


    let destination: DownloadRequest.DownloadFileDestination = { _, _ in

      let documentsURL:NSURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as    NSURL

      print(“***documentURL: “,documentsURL)

      let PDF_name : String = “Downloded_PDF_Name”

      let fileURL = documentsURL.appendingPathComponent(PDF_name)

      print(“***fileURL: “,fileURL ?? “”)

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

    }, to: destination).downloadProgress(closure: { (prog) in

      hud.progress = Float(prog.fractionCompleted)

    }).response { response in


      hud.hide(animated: true)

      if response.error == nil, let filePath = response.destinationURL?.path    {

        print(“File Path”,filePath)


        //Open this filepath in Webview Object


        let fileURL = URL(fileURLWithPath: filePath)

        let request = URLRequest(url: fileURL)





About the author

Swarupa Doiphode
By Swarupa Doiphode