Carlos
Carlos

Reputation: 5445

Swift IOS: How to perform a REST POST request

I am trying to implement a POST with raw text to path, I have tried using NSMutableURLRequest and specifying the following

request.HTTPMethod = "POST"
request.HTTPBody = "some strings here"

I did not manage to get much further than that as I failed miserably while implementing the session.uploadTaskWithRequest.


This however is what I got working fine for a GET request;

private func get(path: String)
{
    let url = NSURL(string: path)
    let session = NSURLSession.sharedSession()

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

        println("JSON recieved")
        if(error)
        {
            println(error.localizedDescription)
        }
        println("Parsing JSON")
        var err: NSError?
        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
        if(err != nil)
        {
            println("Json error");
        }
        println("Building Array result list from JSON")
        var results = jsonResult["results"] as NSArray
        self.delegate?.didReceiveAPIResult(jsonResult)
        println("Done with JSON response")

    })
    task.resume()
}

Upvotes: 3

Views: 6427

Answers (1)

Rafał Sroka
Rafał Sroka

Reputation: 40030

Here you go:

let request = NSMutableURLRequest(URL: yourURL)
request.HTTPMethod = "POST"

let data = yourString.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().uploadTaskWithRequest(request,
           fromData: data)

task.resume()

Upvotes: 4

Related Questions