Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Rob Mount
8,658 PointsExpansion of Networking Concept in Swift iOS track
I'm familiar with Android, but I'm migrating into iOS. I'm trying to figure out how to best send request data via POST using the NSURLSession and related classes. I found the weather app videos helpful for URL requests with no appended request parameters, but I'd like to send information as well as receive.
This is what I've come up with by using Google and the API Docs. This currently works with my servlet, but I'm looking for best practices feedback here. This is not how my final implementation will be, this is what I've been using in my playground so don't fret over how I handle the response.
Please provide suggestions on how to better handle this, if any.
var request = NSMutableURLRequest(URL: NSURL(string: "enter url here"))
request.HTTPMethod = "POST"
var dataString = "NAME=myname&PASSWORD=mypassword"
var requestBodyData: NSData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
request.HTTPBody = requestBodyData
let sharedPOSTSession = NSURLSession.sharedSession()
let task:NSURLSessionDownloadTask = sharedPOSTSession.downloadTaskWithRequest(request, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if(error == nil){
let dataPOSTObject = NSData(contentsOfURL: location)
let loginPOSTDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataPOSTObject, options: nil, error: nil) as NSDictionary
println(loginPOSTDictionary["permissions"]!)
}else{
println(error)
}
})
task.resume()