我尝试使用NSURLSession的过程并不顺利:How to download PDF use NSURLSession POST with headers and body parameters? 。因此我尝试使用Alamofire,但始终失败。这是我的代码:
func callAPIMoneyReport() {
let param = HTTPBody.moneyReportBody(contactId: contactIdentifier!)
print("param: \(String(describing: param))")
let url = NSURL(string:Constant.getAPIMONEYReport())
print("MONEY REPORT URL:\(String(describing: url!))")
Alamofire.request(Constant.getAPIMONEYReport(), method: .post, parameters: param, encoding: JSONEncoding.default, headers: ConnectionManager.sharedIns.getHTTPHeadersRefreshToken())
.responseObject{ (response: DataResponse<MainResponse>) in
switch(response.result) {
case .success(_):
print("MONEY report success")
if response.result.value != nil {
self.moneyReportModel = response.result.value
let status = self.moneyReportModel?.status
let statusCode = response.response?.statusCode
print("statusCode:\(String(describing: statusCode))")
if(statusCode == 200){
}else{
AlertViewUtil.sharedIns.showAlertFeedback(self, messageText: status!, actionButton1: Wordings.BTN_CLOSE, actionButton2: "")
}
}
break
case .failure(_):
print("MONEY report failure")
break
}
}
}
更新: 尝试使用此代码成功,但无法下载PDF:
Alamofire.request(Constant.getAPIMONEYReport(), method: .post, parameters: param, encoding: JSONEncoding.default, headers: ConnectionManager.sharedIns.getHTTPHeadersRefreshToken())
.responseData { response in
print("request:\(request)")
print("response:\(response.data!)")
}
更新也请尝试使用此代码,但找不到pdf:
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0];
let fileURL = documentsURL.appendingPathComponent("family-money.pdf")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(Constant.getAPIMONEYReport(), method: .post, parameters: param, encoding: JSONEncoding.default, headers: ConnectionManager.sharedIns.getHTTPHeadersRefreshToken(), to: destination)
.response { result in
self.dismissProgressDialog()
if let error = result.error {
print("MONEY report failure")
} else {
print("MONEY report success")
let vc = UIDocumentInteractionController(url: result.destinationURL!)
vc.delegate = self
vc.presentPreview(animated: true)
}
}
获取PDF的正确代码是什么? 更新就可以了,因为忘了输入以下代码:
vc.name = result.destinationURL!.lastPathComponent