我的代码正在向我的PHP端点正确执行HTTP POST请求。但是,我需要发送的所有数据都没有到达。这是我发送图像和其他参数的代码。我遇到的问题是PHP代码无法识别键值对(即$ _POST [' DATE'])。在我的PHP代码中,我回显所有POST字典值,它们都是空的。
var imageData : NSData = UIImageJPEGRepresentation(Record.sharedInstance.picture, 1.0)
let url = NSURL(string:"URL")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
let boundary = "Boundary-\(NSUUID().UUIDString)"
let contentType = "mulitpart/form-data; boundary=\(boundary)"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
var body = NSMutableData()
var tempData = NSMutableData()
let fileName = "sharkImage" + ".jpg"
let parameterName = "PHOTOGRAPH"
let mimeType = "image/jpeg"
let fileNameContentDisposition = String(fileName) != nil ? "filename=\"\(fileName)\"" : ""
let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\";\(fileNameContentDisposition)\r\n"
println(Record.sharedInstance.mImagePath)
tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
tempData.appendData("Content-Type : \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
tempData.appendData(imageData)
tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
body.appendData(tempData)
body.appendData(buildBody("DATE", boundary: boundary, value: Record.sharedInstance.mDate))
body.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
request.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request.HTTPBody = body
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { data, response, error in
if error != nil {
return
}
// if response was JSON, then parse it
var parseError: NSError?
let responseObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError)
if let responseDictionary = responseObject as? NSDictionary {
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
} else { // if not JSON
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
})
task.resume()