Chris Mikkelsen Chris Mikkelsen - 1 year ago 37
JSON Question

How to POST request in Swift

I have this API
that will return a bool value depending on the email and password you have entered.

My problem is it will always return false despite using the correct email and password.

I was thinking that I might have not sent the right parameter since I created a dictionary containing the email and password. Then passed it on NSJSONSerialization.dataWithJSONObject method

By the way, I was using SwiftyJson.

This is my code

//creates a dictionary and calls the PostRequest method
func attemptLogIn( email: String, password: String) {
let route = loggerURL
let body: [String:String] = ["email":email, "password":password]
makeHTTPPostRequest(route, body: body)

//performs post request
private func makeHTTPPostRequest(path: String, body: [String: AnyObject]) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)

// Set the method to POST
request.HTTPMethod = "POST"

do {
// Set the POST body for the request
let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
request.HTTPBody = jsonBody
let session = NSURLSession.sharedSession()

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
//onCompletion(json, nil)
print("The Response: ")
} else {
//onCompletion(nil, error)
print("The Response: ")
} catch {
// Create your personal error
//onCompletion(nil, nil)


The response is simply a true or false i.e. its not a json object. So i would suggest don't use Swifty son instead use Alamofire.

Following code should work for you:-

let myParameters = [
    "email": "your email id",
    "password": "your password"]

Alamofire.request(.POST, " ", parameters: myParameters)
         .response { request, response, data, error in
if(response == true)
// do your thing

Note: There might be a need to typecast response to bool

Also following is the screenshot of the link you gave, it returns true(and not a json object) [After registration, i tried to login with same credentials]

enter image description here