Search code examples
iosswiftnsdataalamofire

Alamofire get pdf as NSData


I use this alamofire request to get a pdf file, i want to save it as NSData:

func makeDataCall(urlString: String, completionHandler: (responseObject: NSData?, error: NSError?) -> ()) {
    //Perform request
    Alamofire.request(.GET, urlString, headers: ["Authorization": auth])
        .responseData { request, response, responseData in
            print(request)
            print(response)
            print(responseData)
            completionHandler(responseObject: responseData.data, error: nil)
    }
}

In the response i get this:

"Content-Length" = 592783;
"Content-Type" = "application/pdf";

However responseData.data is nil.

What am i doing wrong?


Solution

  • Editing my previous response, I read your question too quickly.

    To download a file like a pdf you should use Alamofire.download rather than request.

    There's a section on it in the docs: https://github.com/Alamofire/Alamofire#downloading-a-file

    just checked with some random pdf from the internet and this works for me just fine:

    let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
    Alamofire.download(.GET, "http://box2d.org/manual.pdf", destination: destination)
      .response { _, _, _, error in
      if let error = error {
        print("Failed with error: \(error)")
      } else {
        print("Downloaded file successfully")
      }
    }