Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 515
James H Avatar asked May 16 '16 01:05

James H


3 Answers

Swift3 bigger example

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()
like image 85
neoneye Avatar answered Nov 16 '22 00:11

neoneye


In Swift 3, use the URLRequest structure instead of NSURLRequest (similarly, NSURLURL, NSURLSessionURLSession, 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")
like image 38
kennytm Avatar answered Nov 16 '22 00:11

kennytm


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")
like image 9
iThanh Avatar answered Nov 15 '22 23:11

iThanh