iOS Sample POST

3 posts / 0 new
Last post
scanovator
iOS Sample POST

Hi, Can anybody show me a sample of how to post a request in iOS (Swift 2) for an optimized route with many waypoints?

The waypoints have to be supplied in json format and that's a little tough!


scanovator
After a lot of trial and

After a lot of trial and error I figured it out, so I'll post it here in case anybody else wants to use it
override func viewDidLoad() {
super.viewDidLoad()

let url = NSURL(string: "https://www.mapquestapi.com/directions/v2/optimizedRoute?key=YOUR_KEY");

//Post request to json
let request = NSMutableURLRequest(URL: url!)
let session = NSURLSession.sharedSession()

let jsonString = ["locations":["123 Main Street Anytown NJ 01350","1 Any Drive Anytown NJ 01350","4 Some Way Anytown NJ"]]

request.HTTPMethod = "POST"

//request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

do {
//let param = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonString, options: [])
} catch {
print(error)
request.HTTPBody = nil
}

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// handle error
guard error == nil
else
{
return
}
print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
let json: NSDictionary?
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
} catch let dataError {
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
print(dataError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
// return or throw?
return
}

// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
let success = parseJSON["success"] as? Int
print("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
}

})

task.resume()

}


MQBrianCoakley
Cool. Thanks for sharing!
Cool. Thanks for sharing!