我试图将PDF文件的NSData作为POST方法中的参数发送到服务器,方法是将PDF转换为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.}

我尝试过的事情:
重启模拟器
重置模拟器的所有设置
阿拉莫菲尔也有同样的错误
尝试不同的模拟器
info.plist中的App Transport Security为YES
只有一个PDF文件(21kb)被上传,其他的没有

最佳答案

你的应用传输安全设置似乎不允许你转到指定的URL。
将此插入应用程序的plist文件:

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

关于ios - 如何在POST方法swift中将NSData作为参数发送,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39100455/

10-15 15:28