How do I make an HTTP "post" request in Swift?
I have a login page for my application where I authenticate and create a post request. I will be grabbing a marker from the API that is provided to me. However, my code doesn't print anything in the print log. Please, help!
@IBAction func submit(sender: AnyObject) {
//creating a function that will connect to API
func connectToWebAPI(){
//setting up the base64-encoded credentials
let userName = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", userName, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(nil)
//creating the request
let url = NSURL(string: "http://www.telize.com/geoip")
var request = NSMutableURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession.sharedSession()
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let urlConnection = NSURLConnection(request: request, delegate: self)
request.HTTPMethod = "POST"
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
if (error != nil) {
println(error)
}
else {
// converting the data into Dictionary
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(jsonResult)
}
})
//fire off the request
task.resume()
}
source to share
Several problems:
-
First you use both
NSURLConnection
andNSURLSession
. This means that you are actually executing the request twice. Currently, whenNSURLConnection
deprecated, you should remove some ofNSURLConnection
this piece of code and only useNSURLSession
. -
Second, when parsing the JSON, you explicitly told it not to report any error (you set the parameter
error
tonil
). You should really look at the error, if any:var parseError: NSError? if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary { println("jsonResult = \(jsonResult)") } else { // if it didn't work, show enough so we can figure out why: println("parseError = \(parseError)") println("response = \(response)") let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) println("responseString = \(responseString)") // this will probably be HTML from the server describing some problem in the request }
Typically these kinds of requests fail because of something wrong with how the original was created NSURLRequest
, but you are not showing us enough information about the problem.
source to share
Here is the final code for anyone looking for an answer.
//setting up the base64-encoded credentials
let userName = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", userName, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(nil)
//creating the request
let url = NSURL(string: "http://www.telize.com/geoip")
var request = NSMutableURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession.sharedSession()
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var parseError: NSError?
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary {
println("jsonResult = \(jsonResult)")
}
else {
//if this didn't work, show enough so we can figure out why:
println("parseError = \(parseError)")
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
})
//fire off the request
task.resume()
}
source to share