如何使用alamofire设置默认的http标头

问题描述 投票:2回答:2

我想设置一个标题,以便一旦用户登录,所有请求都包含一个授权令牌标题。我以为我可以通过调用我的setToken函数在共享的alamofire管理器中设置标题,但我认为我没有正确地做到这一点。我的错是什么?是否有更好的方法为所有alamofire请求设置默认标头?

 class UserService : NSObject {

    static let manager: Alamofire.Manager = Alamofire.Manager(configuration:  NSURLSessionConfiguration.defaultSessionConfiguration())

    class func setToken(token:String){
        manager.session.configuration.HTTPAdditionalHeaders = [
            "x-token": token
        ]

    }

   class func addFriend(user:LoggedUser, uname:String, callback:((success: Bool, errorMsg: String?)->Void)) {

        let params:[String : AnyObject] = ["uname": uname]

        let url = AppConfig.sharedInstance().baseURL() + "/user/\(user.userId!)/friends"
        Alamofire.request(.POST, url , parameters:params, encoding:.JSON)
            .responseJSON(options: .MutableContainers, completionHandler:{ (request, response, JSON, error) -> Void in

        //token is not set in the request
    }

}
alamofire
2个回答
0
投票

您的代码永远不会使用您的自定义管理器,请使用以下代码:

class CustomManager: Manager {
    static public let manager = CustomManager.generateManager()
    class func generateManager()-> CustomManager {
        var defaultHeaders = Alamofire.Manager.defaultHTTPHeaders ?? [:]
        defaultHeaders["x-token""] = "token"
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.HTTPAdditionalHeaders = defaultHeaders
        let manager = CustomManager(configuration: configuration)
        return manager
    }
}

class UserService : NSObject {

   class func addFriend(user:LoggedUser, uname:String, callback:((success: Bool, errorMsg: String?)->Void)) {

        let params:[String : AnyObject] = ["uname": uname]

        let url = AppConfig.sharedInstance().baseURL() + "/user/\(user.userId!)/friends"
        CustomManager.manager(.POST, url , parameters:params, encoding:.JSON)
            .responseJSON(options: .MutableContainers, completionHandler:{ (request, response, JSON, error) -> Void in

        // ...
    }
}

0
投票

所以我的错误是在我发出请求时使用了类函数而不是共享实例。

所以它应该是

Alamofire.Manager.sharedInstance.request(.POST, url , parameters:params, encoding:.JSON)

而不是

Alamofire.request(.POST, url , parameters:params, encoding:.JSON)

© www.soinside.com 2019 - 2024. All rights reserved.