I have a problem with downloading PDF file using NSURLSession
with POST.My download url is different than any other else because it didn't end with file extension name and it also need parameters to download that file.
It's from ASPX base server and return url like that
http://example.com/DownloadPDF.aspx?File=ES2Ges%2BUA1CEe1150UF3uUgEDeCEMoIuOrJCbwjzVKCEfA6%2F1zKxycl6MMWcjvtk
If I have to access the pdf and download it,I have to provide 2 parameters
ConfigKeyID
and AccessToken
.And one thing strange is it was POST request.
Since,Alamofire
only support GET
request in downloading,so,i have to write my own self using NSURLSession
.But,I have problem with accessing the file from my code because it return html page with 401.
Here is the html :
401 - Unauthorized: Access is denied due to invalid credentials.
Server Error
401 - Unauthorized: Access is denied due to invalid credentials.
You do not have permission to view this directory or page using the credentials that you supplied.
Here is my code
protocol PDFDownloadAPIProtocol{
func didSuccessGettingPDF()
func didFailGettingPDF(err:NSError)
}
class PDFDownloadAPI{
var delegate : InvoicePDFDownloadAPIProtocol
init(delegate: InvoicePDFDownloadAPIProtocol){
self.delegate=delegate
}
func post(url:String,accessToken:String,configKey :String){
let url:NSURL = NSURL(string: url)!
print(url)
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let param = "ConfigKeyID=\(configKey)&AccessToken=\(accessToken)"
request.HTTPBody = param.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.downloadTaskWithRequest(request) {
(
let location, let response, let error) in
guard let _:NSURL = location, let _:NSURLResponse = response where error == nil else {
print("Location Error")
self.delegate.didFailGettingPDF(error!)
return
}
let urlContents = try! NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)
guard let _:NSString = urlContents else {
print("Content Error")
self.delegate.didFailGettingPDF(error!)
return
}
print("Downloaded Content : \(urlContents)")
self.delegate.didSuccessGettingPDF()
}
task.resume()
}
func doDownloadData(url : String,accessToken:String,configKey : String){
post(url,accessToken: accessToken,configKey : configKey)
}
}
When i tried with Postman
everything work file and i can even download file from chrome.So,I think there is something wrong with my code.Any Help?