I need to modify response headers in an NSURLResponse. Is this possible?
You can do that, and you'd need NSHTTPURLResponse
not NSURLResponse
, because, in Swift, NSURLResponse
can be used with many protocols rather than just http
, such as ftp
, data:
, or https
. As a result, you can call it to get the meta data info, such as expected content type, mime type and text encoding, while NSHTTURLResponse
is the one responsible of handling HTTP protocol responses. Thus, it is the one to manipulate the headers.
This is a small code that manipulates the header key Server
from the response, and prints the value before and after the change.
let url = "https://www.google.com"
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let response = response {
let nsHTTPURLResponse = response as! NSHTTPURLResponse
var headers = nsHTTPURLResponse.allHeaderFields
print ("The value of the Server header before is: \(headers["Server"]!)")
headers["Server"] = "whatever goes here"
print ("The value of the Server header after is: \(headers["Server"]!)")
}
})
task.resume()