Swift Alamofire add custom header to all requests

倖福魔咒の 提交于 2019-12-30 08:35:27

问题


I tried to add custom header with this:

let manager = Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
    "Authorization": "Token \(token)"
]

But it doesn't work, what am i doing wrong?

I need to add this after login, so that header will be used in all requests.


回答1:


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




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/32758053/swift-alamofire-add-custom-header-to-all-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!