I\'m struggling :( to make an HTTP post request with a custom JSON Body, I have tried Alamofire with the code :
let list = [[Time: 30, IdQuestion: 6510, idPropos
That works fine
let list = [["Time": 30, "IdQuestion": 6510, "idProposition": 10], ["Time": 30, "IdQuestion": 8284, "idProposition": 10]]
let json = ["List":list,"IdQuiz":"102","IdUser":"iOSclient","UserInformation":"iOSClient"]
let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted,error:nil)
let post = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
httpPost("http://my1test.ru/stack/test.php", postData: "val="+post) {res,code in
println(res)
}
Then I wrote a test php file to view the result got from app:
<?
$d = json_decode($_POST['val']);
echo $d->IdUser;
echo "\n".$d->List[0]->IdQuestion;
?>
And I see
Function I used to make POST-request is below:
func httpPost(url:String, postData: String, completion: (String, Int) -> Void) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding);
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36", forHTTPHeaderField: "User-Agent")
request.addValue("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", forHTTPHeaderField: "Accept")
request.addValue("gzip, deflate, sdch", forHTTPHeaderField: "Accept-Encoding")
request.addValue("max-age=0", forHTTPHeaderField: "Cache-Control")
var session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
if let HTTPResponse = response as? NSHTTPURLResponse {
let statusCode = HTTPResponse.statusCode
completion(NSString(data: data, encoding: NSUTF8StringEncoding) as! String, statusCode)
}
})
task.resume()
}