我试图通过将PDF转换为NSData
然后{{1}将PDF文件的POST
作为NSData
方法中的参数发送到服务器转到NSData
,
String
使用let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let getPDFPath = paths.stringByAppendingPathComponent("resume.pdf")
let pdfdata = NSData(contentsOfFile: getPDFPath)
let dataString: String? = "\(pdfdata!)"
像这样上传参数,
NSURLSession
但是它总是给我错误:
let request = NSMutableURLRequest(URL: NSURL(string: "http://someurl/pdf.aspx")!)
request.HTTPMethod = "POST"
let postString = "pdfdata=\(dataString!)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return }
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
我尝试过的事情:
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was
lost." UserInfo={NSUnderlyingError=0x7f8d63f34250 {Error
Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)"
UserInfo={_kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}},
NSErrorFailingURLStringKey=http://someurl/pdf.aspx,
NSErrorFailingURLKey=http://someurl/pdf.aspx,
_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.}
答案 0 :(得分:2)
您的App Transport Security设置似乎不允许您转到指定的网址。 将其插入应用程序的plist文件中:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
答案 1 :(得分:1)
从iOS9开始,出于安全原因,您需要使用https。您可以编辑Info.plist文件并为您的域添加例外。
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
在此处阅读有关App Transport Security的更多信息: https://developer.apple.com/library/prerelease/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33