James Hart James Hart - 2 years ago 131
Swift Question

HTTP Headers w/ NSURLRequest in swift

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
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 {
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?

Answer Source

In Swift 2.2, you use an NSMutableURLRequest if you need to modify it. Then use addValue(_:forHTTPHeaderField:) to add a header.

let request = NSMutableURLRequest(URL: NSURL(string: usersDataPoint)!)
request.addValue("Token \(tokenString)", forHTTPHeaderField: "Authorization")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download