Search code examples
jsonswifthttppostalamofire

What's the best way to make a HTTP post with custom JSON BODY


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, 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 jsons = NSString(data: data!, encoding: NSUTF8StringEncoding)



    Alamofire.request(.POST, "http://myserver.com", parameters: [:], encoding: .Custom({
        (convertible, params) in
        var mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
        mutableRequest.HTTPBody = jsons!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        return (mutableRequest, nil)
    }))
        .response { request, response, data, error in
        let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
           println(dataString)
    }

But this is not working, I should delete the list to make it work, Why I can't have a list in my JSON body

my JSON body looks like :

{
    "IdQuiz" : 102,
    "IdUser" : "iosclient",
    "User" : "iosclient",
    "List":[
        {
        "IdQuestion" : 5,
        "IdProposition": 2,
        "Time" : 32
        },
        {
        "IdQuestion" : 4,
        "IdProposition": 3,
        "Time" : 9
        }
    ]
}

Is there any library or anything you recommend to make this HTTP post request work ?


Solution

  • 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()
    
        }