2016-08-23 81 views
0

我想一个PDF文件的NSData以服务器为POST方法的参数,通过转换PDF成NSData发送,然后NSDataString如何发送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.} 

东西我曾尝试:

  1. 重新启动模拟器
  2. 复位模拟器的所有设置
  3. 与Alamofire同样的错误
  4. 尝试不同的模拟器
  5. 应用传输安全性是在info.plist
  6. 只有一个PDF文件(21kb)上传,其他不是
+0

该错误消息说,你的连接丢失。你确定你有一个可用的互联网连接? – paulvs

+0

是的,pdf下载在同一个网络上完全正常。 –

回答

2

看起来您的App Transport Security设置不允许您转到指定的网址。 在应用程式的plist文件插入此:

<key>NSAppTransportSecurity</key> 
<dict> 
    <key>NSAllowsArbitraryLoads</key> 
    <true/> 
</dict> 
+0

嗨,我也这样做了,忘记添加它,现在编辑问题。它仍然不起作用 –

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> 

了解更多关于应用传输安全位置: https://developer.apple.com/library/prerelease/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33

+0

我刚刚尝试过,它仍然无法正常工作,但上传了小pdf(20kb),但大(100kb)没有 –

+0

您是否在Xcode的项目设置中激活了Sandbox? – ok404

+0

不,我没有,全部关闭 –