Dragos Strugar
Dragos Strugar

Reputation: 1634

POST request doesn't work

Here is my prepareForSegue method

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let vc = segue.destinationViewController as! AllCommentsViewController
    if segue.identifier == "addComment" {
        if let stringText = commentTF.text {
            vc.CommentsArray.append(stringText)

            let urlString = "http://sekaaleksic.cloudlk.com/api/v1/post/comment/\(postId)/submitComment"

            let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
            let session = NSURLSession.sharedSession()
            let params = ["comment=\(stringText)"]

            request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: [])
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.addValue("\(stringText)", forHTTPHeaderField: "comment")
            request.HTTPMethod = "POST"

            let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error -> Void in

                print(request.HTTPBody)
                print(params)
                print(error)
                print(response)
                print(data)
            })

            task.resume()

            }

        }
    }
}

So, what's the problem? As you see, my urlString is where Wordpress API for submitting a comment. postId is an ID of a post.

I should do something like this: $_POST['comment'] = 'some comment message';

But this code isn't working (you can check the number of Comments for specific post on [this link][1])

Here is the XCode Log ->

["test"]
Optional(<5b22636f 6d6d656e 743d7465 7374225d>)
["comment=test"]
nil
Optional(<NSHTTPURLResponse: 0x137bd1300> { URL: http://sekaaleksic.cloudlk.com/api/v1/post/comment/1/submitComment } { status code: 200, headers {
    "Cache-Control" = "no-cache, must-revalidate, max-age=0, no-cache";
    Connection = "Keep-Alive";
    "Content-Encoding" = gzip;
    "Content-Length" = 70;
    "Content-Type" = "application/json";
    Date = "Wed, 10 Feb 2016 14:00:03 GMT";
    Expires = "Wed, 11 Jan 1984 05:00:00 GMT";
    "Keep-Alive" = "timeout=5, max=700";
    Pragma = "no-cache";
    Server = Apache;
    Vary = "Accept-Encoding";
} })
Optional(<7b227374 61747573 223a6661 6c73652c 22657870 6c61696e 223a2243 6f6d6d65 6e742070 6f737420 69732065 6d707479 227d>)



  [1]: http://sekaaleksic.cloudlk.com/api/v1/post/1/countComments

Upvotes: 1

Views: 1577

Answers (1)

brimstone
brimstone

Reputation: 3400

You are encoding the JSON wrong.

Make params equal to:

["comment": stringText]

JSON is used to encode dictionaries, not concatenated strings.

Upvotes: 1

Related Questions