Search code examples
jsonswifthttp-postnsurlsessionnsurlrequest

Get JSON Results with POST Request with Parameters


How can I use a POST request with parameters to get JSON? I know how to do it with a simple GET request. The request url is http://gyminyapp.azurewebsites.net/api/Gym and the parameter query is

{
  "SearchCircle": {
    "Center": {
      "Latitude": 0,
      "Longitude": 0
    },
    "Radius": 0
  },
  "City": "string",
  "ZipCode": 0,
  "Type": "string"
}

I'm wanting to just use the search circle portion of this, which means I can ignore the City and ZipCode fields. I need to provide Latitude/Longitude, which I getting from the current user location. I also need to set the Type to "radius".

For a simple GET request using the GET version of this, I do this.

let url = NSURL(string: "http://gyminyapp.azurewebsites.net/api/Gym")
        let data = NSData(contentsOfURL: url!)
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
            for gym in json as! [AnyObject] {
                gyms.append(gym)
            }
        } catch {
            print("Error")
        }

Solution

  • This is a working code, you just need to put the values of your request parameters.

    let session = NSURLSession.sharedSession()
        let url = "http://gyminyapp.azurewebsites.net/api/Gym"
        let request = NSMutableURLRequest(URL: NSURL(string: url)!)
        request.HTTPMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        let params:[String: AnyObject] = ["Type" : "string","SearchCircle" : ["Radius" : 0, "Center" : ["Latitude" : 0, "Longitude" : 0]]]
        do{
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
            let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
                if let response = response {
                    let nsHTTPResponse = response as! NSHTTPURLResponse
                    let statusCode = nsHTTPResponse.statusCode
                    print ("status code = \(statusCode)")
                }
                if let error = error {
                    print ("\(error)")
                }
                if let data = data {
                    do{
                    let jsonResponse = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
                    print ("data = \(jsonResponse)")
                    }catch _ {
                        print ("OOps not good JSON formatted response")
                    }
                }
            })
            task.resume()
        }catch _ {
            print ("Oops something happened buddy")
        }
    

    Then in the if let data = data you'd need to parse the response. I checked the response, it is JSON formatted array.