Swift: HTTP request with parameters in header

28,471

Solution 1

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 }

Solution 2

i did this.

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

        request.setValue("application-idValue", forKey: "application-id")
        request.setValue("secret-keyValue", forKey: "secret-key")

        session.dataTaskWithRequest(request){(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 3

 //MARK: GET Method
func GETDataFromServerUsingHeaderParameters(nameOfApi : NSString, parameters : NSString, withCurrentTask: RequestType, andDelegate : AnyObject) -> Void {
    if (currentReachabilityStatus != .notReachable){
        //print("Internet Connection Available!")
        currentTask = withCurrentTask
        let respectedURL = NSString(format: "%@%@", GlobalConstants.KBase_Url,nameOfApi,parameters)
        let myRequestUrl = (respectedURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))!
        let url = NSURL(string: myRequestUrl as String)!
        let request = NSMutableURLRequest(url: url as URL)
        request.setValue("application-idValue", forKey: "application-id")
        request.setValue("secret-keyValue", forKey: "secret-key")
        request.httpMethod = "GET"
            let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
            guard let data = data, error == nil else {
                self.showAlertMessage(title: "App Name", message: "Server not responding, please try later")
                self.delegate?.internetConnectionFailedIssue()
                return
            }
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                self.delegate?.internetConnectionFailedIssue()
            }else{
                do {
                    self.responseDictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSDictionary
                    self.delegate?.responseReceived()
                } catch {
                }
            }
        }
        task.resume()
    }else{
        self.showAlertMessage(title: "App Name", message: "No Internet Connection..")
    }
}
Share:
28,471
Tadeáš Broniš
Author by

Tadeáš Broniš

Updated on May 20, 2021

Comments

  • Tadeáš Broniš
    Tadeáš Broniš almost 3 years

    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()
    
  • Said Sikira
    Said Sikira about 8 years
    Check the updated answer. Note that you should not use setValue:forKey: for HTTP headers, since it may not add headers to the HTTP body
  • Keara
    Keara almost 5 years
    Thanks for the answer! Would you (or someone editing this answer) be able to add a note saying which version of Swift this is?