Anybody have an idea how to configure HTTP Headers with NSURLRequest in Swift? I have authentication set up on my server and it only needs a token passed to it but I'm having trouble setting the header
my code:
func getLatestData() {
var loggedInUsersNumber:String = SharingManager.sharedInstance.userID
var usersDataPoint:String = StormDataPoint + loggedInUsersNumber
activityIND.hidden = false
activityIND.startAnimating()
let request = NSURLRequest(URL: NSURL(string: usersDataPoint)!)
let tokenString = SharingManager.sharedInstance.authToken
//request.setValue("Token " + tokenString, forKey: "Authorization")
let urlSession = NSURLSession.sharedSession()
let task = urlSession.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
if let error = error {
print(error)
return }
I created a property "tokenString" to be the token to pass into the header and on the next line where i commented it out. request.setvalue - I popped it in and get an error to the tune of "cannot override data type". All my searches show Objective C help. Is there a better way to try to pass a header in?
var req: URLRequest = /* create requets */
req.setValue("Bearer Y3GzLG2x6wSXihmUGhwGFw", forHTTPHeaderField: "Authorization")
req.timeoutInterval = 10
let task = URLSession.shared.dataTask(with: req, completionHandler: { (data, response, error) in
print("completionHandler invoked")
})
task.resume()
In Swift 3, use the URLRequest
structure instead of NSURLRequest
(similarly, NSURL
↦ URL
, NSURLSession
↦ URLSession
, etc.).
Then use addValue(_:forHTTPHeaderField:)
to add a header.
// swift 3:
var request = URLRequest(url: URL(string: usersDataPoint)!)
request.addValue("Token \(tokenString)", forHTTPHeaderField: "Authorization")
In Swift 2.2, you use an NSMutableURLRequest
if you need to modify it.
// swift 2:
let request = NSMutableURLRequest(URL: NSURL(string: usersDataPoint)!)
request.addValue("Token \(tokenString)", forHTTPHeaderField: "Authorization")
You can create Mutable URL Request, then set value for field name.
let request = NSMutableURLRequest(URL: NSURL(string: yourURLString)!)
request.setValue("\(yourValue)", forHTTPHeaderField: "Header-field-name")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With