Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have many adapters for Alamofire session manager?

Tags:

alamofire

I would like to have many adapters to the same SessionManager, is it possible?

My usecase is:

setup default header from an adapter

if basic_auth: add basic_auth_adapter

if token_auth: add token_auth_adapter

Thanks

like image 244
Idaho Avatar asked Nov 28 '25 00:11

Idaho


2 Answers

Currently in Alamofire 4 you can only use 1 RequestAdapter with each SessionManager. We designed it this way because to help you simplify things and to avoid order issues if there are multiple adapters.

You could easily add all those functions to the same adapter. Our intention was that if an adapter became way too complicated, you could break out the logic into multiple smaller objects. One way you could possibly do this would be to create a smaller adapter for each type of URL request. Then the main adapter called by the SessionManager would inspect the URL request and call the appropriate smaller adapter.

like image 124
cnoon Avatar answered Nov 29 '25 23:11

cnoon


I came up with this solution:

struct MasterAdapter: RequestAdapter {

    let adapters: [RequestAdapter]

    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
        var request = urlRequest
        try adapters.forEach({ request = try $0.adapt(request) })
        return request
    }

}

Now set MasterAdapter with it's child adapters as your adapter on your default or custom SessionManager.

SessionManager.default.adapter = MasterAdapter(adapters: [MyAdapter1(), MyAdapter2()])
like image 22
diegotrevisan Avatar answered Nov 29 '25 23:11

diegotrevisan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!