Lord Vermillion
Lord Vermillion

Reputation: 5414

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?

Upvotes: 3

Views: 6871

Answers (2)

Bruno Camargos
Bruno Camargos

Reputation: 327

In Swift 4 use this code if you want to download a pdf

    let h: HTTPHeaders = [
        "Accept": "application/pdf",
        "Content-Type": "application/pdf",
    ]
    //random document name
    let randomString = NSUUID().uuidString

    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        documentsURL.appendPathComponent("\(randomString).pdf")
        return (documentsURL, [.removePreviousFile])
    }

    Alamofire.download("yourURL",method: .get,headers: h, to: destination).response { response in
        if let destinationUrl = response.destinationURL {
            print("destinationUrl \(destinationUrl.absoluteURL)")
        }
    }

Upvotes: 0

66o
66o

Reputation: 756

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

Upvotes: 6

Related Questions