Reputation: 5074
I am still learning Swift and I am trying to make a POST request to my web service via my new iOS App written in Swift.
I need to know how to add 2 headers to my already existing code. Also am I adding the parameters correctly?
What I have so far:
let myUrl = NSURL(string: "https://MY-MOBILE-SERVICE.azure-mobile.net/api/login");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let postString = "[email protected]&password=123";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
print("response = \(response)")
}
task.resume()
Here are the Headers I need to add to this request:
X-ZUMO-APPLICATION: 45634243542434
ACCEPT: application/json
How do I attach these headers to my request?
Upvotes: 2
Views: 1714
Reputation: 11807
if you use alamofire, this should work, it also eases things for you so you choose get or post
var pars2 : Dictionary<String,String> = ["api_key":"value"]
Alamofire.request(.POST, "someURLString" ,parameters: pars2).responseJSON()
{
(request, response, data, error) in
if(data != nil)
{
self.countryIDArray.removeAll(keepCapacity: false)
var status = data!["status"]!! as! String
}
}
Upvotes: 0
Reputation: 947
Have a look at the reference docs: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/#//apple_ref/occ/instm/NSMutableURLRequest/setValue:forHTTPHeaderField:
so you would do: request.setValue("ACCEPT" forHTTPHeaderField: "application/json")
Upvotes: 1