How to send JSON data using POST method swift - ios

How to send JSON data using POST method to server in SWIFT
For Objective C i use this
NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:validEmailTF.text forKey:#"email"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:#"r=%#",jsonInputString];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#",forgetPasswordUrl]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData != nil)
{
jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"Values =======%#",jsonDict);
}
Convert this code in Swift language.
Thanks

You can try this, may be it will help you
let request = NSMutableURLRequest(URL: NSURL(string: "Your forgetPasswordUrl")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let params = ["email":validEmailTF.text] as Dictionary<String, String>
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")})
task.resume()

Simply converted your code to swift without tuning your code.
Try this:
var get: NSMutableDictionary = NSMutableDictionary()
get["email"] = validEmailTF.text
var jsonData: NSData = NSJSONSerialization.dataWithJSONObject(get, options: kNilOptions, error: nil)
var jsonInputString: String = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
var post: String = NSString(format: "r=%#",jsonInputString)
var get: NSMutableDictionary = NSMutableDictionary()
var url: NSURL = NSURL(string: "\(forgetPasswordUrl)")
var postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)
var postLength: String = "\(postData.length())"
var request: NSMutableURLRequest = NSMutableURLRequest.requestWithURL(url, cachePolicy: NSURLRequestReloadIgnoringCacheData, timeoutInterval: 120.0)
request.URL = url
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData
var error: NSError
var response: NSURLResponse
var responseData: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
if responseData != nil {
jsonDict = NSJSONSerialization.JSONObjectWithData(responseData, options: kNilOptions, error: &error)
print("Values =======\(jsonDict)")

Related

Working in ObjC, not in swift. Whats wrong I am doing with JSON parsing in swift

I just wanted to Parse JSON from URL,
The code below written in ObjC is working well and giving me correct response,
but the code written in swift 3.1, not giving correct response.
Giving me 500 Internal Error
Whats wrong I am doing.
Can anyone guide.
Thanks in advance.
I also tried to use converter from ObjC to Swift.
But it fails with some errors, though I solve those errors, but still not giving correct output.
ObjC code below.
-(void)comparedatainserturl
{
NSError *error;
NSMutableArray *arr=[[NSMutableArray alloc]init];
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setObject:#"e639e129d0f3ab7d" forKey:#"imei_no"];
[dict setObject:#"2017-08-29 12:18:44" forKey:#"current_time"];
[dict setObject:#"0" forKey:#"tbl_offer_details"];
[dict setObject:#"0" forKey:#"tbl_card_type"];
[dict setObject:#"0" forKey:#"tbl_dashboard"];
[dict setObject:#"0" forKey:#"tbl_category_details"];
[dict setObject:#"0" forKey:#"tbl_sub_category_details"];
[dict setObject:#"0" forKey:#"tbl_payment_option"];
[dict setObject:#"0" forKey:#"tbl_payment_option_provider"];
[dict setObject:#"0" forKey:#"tbl_like_favorite_share"];
[dict setObject:#"0" forKey:#"tbl_user_details"];
[arr addObject:dict];
NSLog(#"arra :- %#",[arr description]);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *string = [NSString stringWithFormat:#"data=%#",jsonString];
NSLog(#"jsonData as string:\n%#", string);
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSString *urlString=[NSString stringWithFormat:#"%#",#"http://admin.scontos.com/index.php/Android_api/Offers_download"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: data];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"gotresponsestring=%#", resSrt);
}
Swift Code below,
func comparedatainserturl() {
var arrayParams : NSDictionary = [:]
arrayParams = ["imei_no":"e639e129d0f3ab7d","current_time":"2017-08-2911:08:26","tbl_offer_details":"0","tbl_card_type":"0","tbl_dashboard":"0","tbl_category_details":"0","tbl_sub_category_details":"0","tbl_payment_option":"0","tbl_payment_option_provider":"0","tbl_like_favorite_share":"0","tbl_user_details":"0"]
print(arrayParams)
let valueArr : Array = [arrayParams]
print(valueArr)
let jsonData: Data? = try! JSONSerialization.data(withJSONObject: valueArr, options: .prettyPrinted)
let jsonString = String(data: jsonData!, encoding: String.Encoding.utf8)
let string: String = "data=\(jsonString)"
print("jsonData as string:\n\(string)")
let dataa: Data? = string.data(using: String.Encoding.utf8)
var _: NSError?
let url1:URL = URL(string:"http://admin.scontos.com/index.php/Android_api/Offers_download")!
let request:NSMutableURLRequest = NSMutableURLRequest(url: url1)
request.httpMethod = "POST"
request.httpBody = dataa
var response: URLResponse?
do{
let urlData: Data? = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response)
let resstr = NSString(data: urlData!, encoding: String.Encoding.utf8.rawValue)
print("Response is \(resstr! as String)")
}catch{
print(error)
}
}
In your swift code you are appending the following string.
let jsonString = String(data: jsonData!, encoding: String.Encoding.utf8)
/In following line you are appending JsonString with optional value with optional key word with this "()". So you need to unwrap the optional value/
let string: String = "data=\(jsonString!)"
Your code is sending a body of a request that effectively looks like:
data=[
{
"key1" : "value1",
"key2" : "value2", ...
}
]
That is incorrect.
If your server was expecting just the JSON, you should send the JSON without the data= prefix.
If your server is expecting a application/x-www-form-urlencoded request, then that value cannot have spaces, newline characters, or any other reserved characters in it. In this case, you have to "percent escape" the body of the request.
You should confirm precisely what the web service is expecting, and adjust your code accordingly.
Unrelated, I'd retire the NS classes and stay within Swift. So, assuming you wanted to just send JSON, the code might look like:
func comparedatainserturl() {
let arrayParams = [
[
"imei_no":"e639e129d0f3ab7d",
"current_time":"2017-08-2911:08:26",
"tbl_offer_details":"0",
"tbl_card_type":"0",
"tbl_dashboard":"0",
"tbl_category_details":"0",
"tbl_sub_category_details":"0",
"tbl_payment_option":"0",
"tbl_payment_option_provider":"0",
"tbl_like_favorite_share":"0",
"tbl_user_details":"0"
]
]
let data = try! JSONSerialization.data(withJSONObject: arrayParams)
let jsonString = String(data: data, encoding: .utf8)!
let string: String = "data=" + jsonString
print("jsonData as string:\n\(string)")
let url1 = URL(string:"http://admin.scontos.com/index.php/Android_api/Offers_download")!
var request = URLRequest(url: url1)
request.httpMethod = "POST"
request.httpBody = data
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print(error)
return
}
guard let data = data else { return }
let string = String(data: data, encoding: .utf8)
print("response is \(string)")
}
task.resume()
}
Or, if the server was expecting x-www-form-urlencoded request:
let data = try! JSONSerialization.data(withJSONObject: arrayParams)
let jsonString = String(data: data, encoding: .utf8)!
let string: String = "data=" + jsonString.addingPercentEncodingForQuery()!
let url1 = URL(string:"http://admin.scontos.com/index.php/Android_api/Offers_download")!
var request = URLRequest(url: url1)
request.httpMethod = "POST"
request.httpBody = string.data(using: .utf8)
Where you percent escape using this routine, adapted from Alamofire's escape routine:
extension String {
public func addingPercentEncodingForQuery() -> String? {
let generalDelimitersToEncode = ":#[]#" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)
return addingPercentEncoding(withAllowedCharacters: allowed)
}
}

How to post raw data in swift 3?

If I post raw data using Postman, response is coming. I am using this code
var dict = Dictionary<String, Any>()
dict = ["user_id" :userid as AnyObject, "type" :type as AnyObject, "complaint_id" :complaintId as AnyObject, "auth_code" : authCode as AnyObject, "isSkip" :isSkip as AnyObject]
let url:URL = URL(string: "http://development.easystartup.org/prigovo/Backend/detailed_complaint/index.php")!
let session = URLSession.shared
var postData = NSData()
do{
postData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData!
}catch {
print("error")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
// request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
request.setValue("\(postData.length)", forHTTPHeaderField: "Content-Length")
request.setValue("text/html", forHTTPHeaderField: "Content-Type")
request.setValue("json/application", forHTTPHeaderField: "Accept")
request.httpBody = postData as Data
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
print(dataString ?? "no data")
}
task.resume()
Getting data of 0 bytes everyTime. Already tried with Alamofire but no response.
Also I tried in Objective C where I am getting response, code is :
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/html" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
{
//error
NSLog(#"error");
return #"";
}
else
{
NSLog(#"No error");
NSString *charlieSendString = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
NSLog(#"data come : %#",charlieSendString);
return charlieSendString;
}
Posted "dict" in Log :
["complaint_id": COMBRD1, "user_id": USR9, "type": complaint_brand, "auth_code": KL1hwYrAhNVnSgT, "is_skip": 2]
var dict = Dictionary<String, Any>()
dict = ["user_id" :userid, "type" :type, "complaint_id" :complaintId,"auth_code" : authCode, "is_skip" :isSkip]
var jsonData = NSData()
// var dataString2 :String = ""
do {
jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) as NSData
// you can now cast it with the right type
} catch {
print(error.localizedDescription)
}
let url:URL = URL(string: "http://Backend/detailed_complaint/index.php")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("\(jsonData.length)", forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData as Data
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
print("no data",dataString ?? "no data")
}
task.resume()

Can't get allHeaderFields from NSURLConnection.sendSynchronousRequest with swift

As the response required for NSURLConnection.sendSynchronousRequest is now requiring NSURLResponse not NSHTTPURLResponse I can't get allHeaderFields.. Is there something I can do here?
var newRequest: NSMutableURLRequest = NSMutableURLRequest(URL: request.URL)
newRequest.HTTPMethod = "HEAD"
var response: NSURLResponse
NSURLConnection.sendSynchronousRequest(newRequest, returningResponse: &response, error: nil)
if response.respondsToSelector(Selector(allHeaderFields)) {
let allHeaders = response.allHeaderFields
}
In the old Objective-C version I was doing this which no longer works in swift..
NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[request URL]];
[newRequest setHTTPMethod:#"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:newRequest returningResponse:&response error: NULL];
if ([response respondsToSelector:#selector(allHeaderFields)]) {
NSDictionary *dictionary = [response allHeaderFields];
}
Rather than respondsToSelector, you should use optional binding, casting it to a NSHTTPURLResponse:
let newRequest: NSMutableURLRequest = NSMutableURLRequest(URL: url)
newRequest.HTTPMethod = "HEAD"
var response: NSURLResponse?
NSURLConnection.sendSynchronousRequest(newRequest, returningResponse: &response, error: nil)
if let httpResponse = response as? NSHTTPURLResponse {
// use `httpResponse.allHeaderFields`
}

Where did setHTTPMethod, setURL and setHTTPBody go in swift?

I am trying to implement HTTP requests.
Here is the objective C implementation
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
I started by writing:
let request = NSMutableURLRequest()
request .setValue(postLength, forHTTPHeaderField: "Content-Lenght")
request .setValue(application/json, forHTTPHeaderField: Accept)
1.The json request is giving me an error.
2.I cannot convert the setURL and SetHTTPBody from objective C to swift. I could not find
the option for these.
Any help would be appreciated.
Thank you.
They have become properties. Most setter methods with a single argument have become properties.
The problem with your json line is you did not have quotes around "Accept."
let request = NSMutableURLRequest()
request.url = url
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField:"Content-Length")
request.setValue("application/json", forHTTPHeaderField:"Accept")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
request.postBody = postData
Here is how i do it in swift :
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
var request: NSMutableURLRequest?
let HTTPMethod: String = "POST"
var timeoutInterval: NSTimeInterval = 60
var HTTPShouldHandleCookies: Bool = false
request = NSMutableURLRequest(URL: url)
request!.HTTPMethod = HTTPMethod
request!.timeoutInterval = timeoutInterval
request!.HTTPShouldHandleCookies = HTTPShouldHandleCookies
let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
let contentType = "multipart/form-data; boundary=\(boundary)"
request!.setValue(contentType, forHTTPHeaderField:"Content-Type")
var body = NSMutableData();
let tempData = NSMutableData()
let fileName = filenames + ".jpg" //"prueba.jpg"
let parameterName = "userfile"
let mimeType = "application/octet-stream"
tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
let fileNameContentDisposition = fileName != nil ? "filename=\"\(fileName)\"" : ""
let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n"
tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData(imageData)
tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(tempData)
body.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request!.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request!.HTTPBody = body
var vl_error :NSErrorPointer = nil
var responseData = NSURLConnection.sendSynchronousRequest(request,returningResponse: nil, error:vl_error)
var results = NSString(data:responseData, encoding:NSUTF8StringEncoding)
println("finish \(results)")
I am calling the json on login button click
#IBAction func loginClicked(sender : AnyObject){
var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
if(err) {
println(err!.localizedDescription)
}
else {
var success = json2["success"] as? Int
println("Succes: \(success)")
}
})
task.resume()
}
Here, I have made a seperate dictionary for the parameters.
var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"] as NSDictionary
return params
}

NSURLSession with Token Authentication

I have the following code in my iOS project and I want to convert to use NSURLSession instead of NSURLConnection. I am querying a REST API which uses a token-based HTTP Authentication scheme but I cannot find an example of how to do it.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:#"Username"];
NSString *token = //GET THE TOKEN FROM THE KEYCHAIN
NSString *authValue = [NSString stringWithFormat:#"Token %#",token];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
if ([NSURLConnection canHandleRequest:request]){
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[NSURLConnection sendAsynchronousRequest:request queue:self.fetchQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200){
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil];
//Process the data
}
}
}];
}
You can rewrite it using NSURLSession as follows
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *token ; //GET THE TOKEN FROM THE KEYCHAIN
NSString *authValue = [NSString stringWithFormat:#"Token %#",token];
//Configure your session with common header fields like authorization etc
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{#"Authorization": authValue};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSString *url;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200){
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil];
//Process the data
}
}
}];
[task resume];
This is in Swift, but the logic is the same:
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let url = NSURL(string: "some url")
let request = NSMutableURLRequest(URL: url!)
request.setValue("value", forHTTPHeaderField: "header field")
let urlSession = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
let dataTask = urlSession.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
}
dataTask.resume()
Set the Authorization header on your URLSession configuration, or directly on your request.
Be advised that Apple says you "should not" attempt to modify the Authorization header in your URLSession configuration:
An URLSession object is designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers:
Authorization
...
It is, however, possible. If you want to do this, ensure that you set the header configuration before you create the URLSession. It's not possible to modify headers on an existing URLSession.
Here is a Swift playground that shows different scenarios:
import Foundation
// 1: Wrong -- mutating existing config for existing URLSession is no-op
var session = URLSession.shared
session.configuration.httpAdditionalHeaders = ["Authorization": "123"]
let url = URL(string: "https://postman-echo.com/get")!
session.dataTask(with: url) { (data, resp, err) in
if let data = data {
let str = String(bytes: data, encoding: .utf8)!
let _ = str
}
}.resume() // no authorization header
// 2: Setting headers on an individual request works fine.
var request = URLRequest(url: url)
request.addValue("456", forHTTPHeaderField: "Authorization")
session.dataTask(with: request) { (data, resp, err) in
if let data = data {
let str = String(bytes: data, encoding: .utf8)!
let _ = str
}
}.resume() // "headers": { "authorization": "456" }
// 3: You can set headers on a new URLSession & configuration
var conf = URLSessionConfiguration.default
conf.httpAdditionalHeaders = [
"Authorization": "789"
]
session = URLSession(configuration: conf)
session.dataTask(with: url) { (data, resp, err) in
if let data = data {
let str = String(bytes: data, encoding: .utf8)!
let _ = str
}
}.resume() // "headers": { "authorization": "789" }

Resources