如何发送NSData的作为参数POST方法迅速
我想一个PDF文件的NSData
以服务器为POST
方法的参数,通过转换PDF成NSData
发送,然后NSData
到String
,如何发送NSData的作为参数POST方法迅速
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.}
东西我曾尝试:
- 重新启动模拟器
- 复位模拟器的所有设置
- 与Alamofire同样的错误
- 尝试不同的模拟器
- 应用传输安全性是在
info.plist
- 只有一个PDF文件(21kb)上传,其他不是
看起来您的App Transport Security设置不允许您转到指定的网址。 在应用程式的plist文件插入此:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
嗨,我也这样做了,忘记添加它,现在编辑问题。它仍然不起作用 –
由于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>
我刚刚尝试过,它仍然无法正常工作,但上传了小pdf(20kb),但大(100kb)没有 –
您是否在Xcode的项目设置中激活了Sandbox? – ok404
不,我没有,全部关闭 –
该错误消息说,你的连接丢失。你确定你有一个可用的互联网连接? – paulvs
是的,pdf下载在同一个网络上完全正常。 –