Swift Alamofire add custom header to all requests

前端 未结 4 1769
北荒
北荒 2021-01-12 11:13

I tried to add custom header with this:

let manager = Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
    \"Authorization\": \         


        
相关标签:
4条回答
  • 2021-01-12 11:44

    You should not append Authorization headers in this way. They should always be appended using the headers parameter in the request method as shown by @Glenn.

    Additionally, if you need to append other headers to a configuration, you need to create a custom configuration, set the header values, then create a new Manager instance with the new configuration. Adding headers to a configuration after it has already been used to create a URL session results in undefined behavior depending on which version of which OS you are running on. We have many tests in Alamofire demonstrating this varying behavior.

    0 讨论(0)
  • 2021-01-12 11:54

    I got tired trying to manually replace the whole app by adding headers to 100+ of my requests. I opted for a more lazier approach:

    Make an AlamofireManagerExtension.swift and use the following code:

    import Foundation
    import Alamofire
    
    extension Manager {
        public func myRequest(
            method: Alamofire.Method,
            _ URLString: URLStringConvertible,
            parameters: [String: AnyObject]? = nil,
            encoding: ParameterEncoding = .URL,
            headers: [String: String]? = ["MY-STATIC-API-KEY" : "BLAHBLAHBLAH"])
            -> Request
        {
            return Manager.sharedInstance.request(
                method,
                URLString,
                parameters: parameters,
                encoding: encoding,
                headers: headers
            )
        }
    }
    

    Then, ctrl-shift-f on your xcode project, search for sharedInstance.request or whatever you do to make requests (all of my code follows this pattern) and replace it with sharedInstance.myRequest (Be sure not to change the extension itself's sharedInstance.request) and voila:

    Globally changed custom header for all requests!

    If you wanted to add in custom keys, of course you can prepend methods with the replace method like sharedInstance.request(method: ...) to sharedInstance.myRequest(customKeys: ..., method: ...) if you need custom variables.

    0 讨论(0)
  • 2021-01-12 11:55

    I don't know where you do that but my AlomoFire requests look like :

     Alamofire.request(.GET, urlPath, parameters: parameters, headers: ["X-API-KEY": apiKey, "Content-type application":"json", "Accept application" : "json"]).responseJSON() { (req,res, data, error) in //blah blah }
    

    My guess is that you can put your header information into that headers array

    0 讨论(0)
  • 2021-01-12 12:03

    A way to do this is to use a RequestAdapter as demoed on the Alamofire advanced usage documentation.

    0 讨论(0)
提交回复
热议问题