I have the following code in my iOS
project and I want to convert to use NSURLSession
instead of NSURLConnection
. I am querying a
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" }