Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save cmoulton/ab674eb7bcb5aa1a0580fc8ba5176f6b to your computer and use it in GitHub Desktop.
Save cmoulton/ab674eb7bcb5aa1a0580fc8ba5176f6b to your computer and use it in GitHub Desktop.
Custom HTTP Headers with Swift 3 or 4 and Alamofire 4.0-4.7: See https://grokswift.com/custom-headers-alamofire4-swift3/ for explanations
// MARK: - Adding a header to a single request
func doRequestWithHeaders1() {
let headers: HTTPHeaders = [
"X-Mashape-Key": MY_API_KEY,
"Accept": "application/json"
]
Alamofire.request("https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh", headers: headers)
.responseJSON { response in
debugPrint(response)
}
// MARK: - To make sure the headers are sent, use debugPrint on the request
let request = Alamofire.request("https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh", headers: headers)
.responseJSON { response in
debugPrint(response)
}
debugPrint(request)
}
// MARK: - Adding headers to all requests in the session
// store sessionManager so it doesn't get deallocated while we're waiting for the network call to finish
var sessionManager: Alamofire.SessionManager?
func doRequestWithHeaders2() {
// get the default headers
var headers = Alamofire.SessionManager.defaultHTTPHeaders
// add your custom headers
headers["API-Version"] = "2.0"
headers["X-Mashape-Key"] = MY_API_KEY
// create a custom session configuration
let configuration = URLSessionConfiguration.default
// add the headers
configuration.httpAdditionalHeaders = headers
// create a session manager with the configuration
self.sessionManager = Alamofire.SessionManager(configuration: configuration)
// make calls with the session manager
sessionManager?.request("https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh")
.responseJSON { response in
debugPrint(response)
}
}
// MARK: - Add headers when using a URLRequest
func doRequestWithHeaders3() {
if let url = URL(string: "https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh") {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue(MY_API_KEY, forHTTPHeaderField: "X-Mashape-Key")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
Alamofire.request(urlRequest)
.responseJSON { response in
debugPrint(response)
}
}
}
// Alternatively:
func doRequestWithHeaders4() {
if let url = URL(string: "https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh") {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
var headers: HTTPHeaders
if let existingHeaders = urlRequest.allHTTPHeaderFields {
headers = existingHeaders
} else {
headers = HTTPHeaders()
}
headers["X-Mashape-Key"] = MY_API_KEY
headers["Accept"] = "application/json"
urlRequest.allHTTPHeaderFields = headers
let request = Alamofire.request(urlRequest)
.responseJSON { response in
debugPrint(response)
}
debugPrint(request)
}
}
// MARK: - Use an Alamofire RequestAdapter to add headers to all calls in the session
class MashapeHeadersAdapter: RequestAdapter {
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
var urlRequest = urlRequest
urlRequest.setValue(MY_API_KEY, forHTTPHeaderField: "X-Mashape-Key")
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
return urlRequest
}
}
func doRequestWithHeaders5() {
// Then to make the call:
// get a session manager and add the request adapter
let sessionManager = Alamofire.SessionManager.default
sessionManager.adapter = MashapeHeadersAdapter()
// make calls with the session manager
let request = sessionManager.request("https://mashape-community-urban-dictionary.p.mashape.com/define?term=smh")
.responseJSON { response in
debugPrint(response)
}
debugPrint(request)
}
@vsg24
Copy link

vsg24 commented Mar 28, 2018

Good one

@bartleby
Copy link

bartleby commented May 7, 2018

nice

@CoalWood
Copy link

CoalWood commented Jun 23, 2018

I found your examples to be a BIG Help. Here is one I am using that has "headers" for Yelp Authorization. Apparently Yelp very recently changed how they handle Authorization so not may examples exist as of this post time. So, here it is:

func doMashape() -> Void {

let fileURL = "https://api.yelp.com/v3/businesses/search?term=Restaurants"
let parameters : Parameters = ["radius": "10000", "latitude": "29.94", "longitude": "-85.41"]
let headers: [String : String] = ["Authorization": "Bearer <YOUR YELP APP_ID GOES HERE>"]
Alamofire.request(fileURL, method: .get, parameters: parameters, headers: headers).responseJSON {
  response in
    if let receivedString = response.result.value {
      print()
      print("Here \(receivedString)")
    }
}

Note: This entry does not include the <> and has a simple space between Bearer and APP_ID.

@lakshaychhabra
Copy link

How to Handle errors in URL in it?
Suppose by chance user entered character like "/" then it crashes the program

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment