Alamofire 获取 pdf 作为 NSData

Alamofire get pdf as NSData

我使用这个 alamofire 请求来获取一个 pdf 文件,我想将它保存为 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)
    }
}

在回复中我得到了这个:

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

然而 responseData.data 为零。

我做错了什么?

编辑我之前的回复,我读你的问题太快了。

要下载 pdf 等文件,您应该使用 Alamofire.download 而不是 request.

文档中有一节是关于它的: https://github.com/Alamofire/Alamofire#downloading-a-file

刚刚检查了一些来自互联网的随机 pdf,这对我来说很好:

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

在Swift 4中,如果你想下载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)")
        }
    }