我使用此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
为零。
我做错了什么?
答案 0 :(得分:6)
编辑我以前的回复,我过快地读了你的问题。
要下载像pdf这样的文件,您应该使用 Alamofire.download 而不是请求。
文档中有关于它的部分: 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")
}
}
答案 1 :(得分:0)
在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)")
}
}