swifthttphttp-headershttp-requesthttp-request-parameters

Swift: HTTP request with parameters in header


i need to send an HTTP request, I can do that but my API in Backendless requires application-id and secret-key in HTTP Request Header. Can you help how to add it into my code? Thanks

let urlString = "https://api.backendless.com/v1/data/Pub"
    let session = NSURLSession.sharedSession()
    let url = NSURL(string: urlString)!

    session.dataTaskWithURL(url){(data: NSData?,response: NSURLResponse?, error: NSError?) -> Void in

        if let responseData = data
        {
            do{
                let json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments)
                print(json)
            }catch{
                print("Could not serialize")
            }
        }

    }.resume()

Solution

  • Swift 5+, 4.1+ and Swift 3

    var request = URLRequest(url: url)
    request.setValue("secret-keyValue", forHTTPHeaderField: "secret-key")
    
    URLSession.shared.dataTask(with: request) { data, response, error in }
    

    Swift 2.2

    Wrap your NSURL into NSMutableRequest like this:

    let request = NSMutableURLRequest(URL: url)
    

    And then use this method to add header to your request object:

    request.setValue("secret-keyValue", forHTTPHeaderField: "secret-key")
    

    And instead of using dataTaskWithURL: use dataTaskWithRequest: method.

    session.dataTaskWithRequest(request){
    (data: NSData?,response: NSURLResponse?, error: NSError?) -> Void in }