如何在POST方法swift中发送NSData作为参数

时间:2016-08-23 11:54:00

标签: ios swift pdf nsurlsession

我试图通过将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()

我尝试过的事情:

  1. 重新启动模拟器
  2. 重置模拟器的所有设置
  3. 与Alamofire相同的错误
  4. 尝试了不同的模拟器
  5. 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.}
  6. 中的应用传输安全性为YES
  7. 只有一个PDF文件(21kb)上传,其他不是

2 个答案:

答案 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