Emptyless
Emptyless

Reputation: 3050

Add GET parameter in request adapter of Alamofire

I am trying in the Request Adapter of Alamofire to add a GET parameter. However in the request adapter I am only able to add HTTPHeader fields.

Currently my request adapter looks like:

// MARK: - RequestAdapter

func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
    if let url = urlRequest.url, url.lastPathComponent.hasPrefix(baseURLString) {
        var urlRequest = urlRequest

        // Want to inject param here
        // e.g. urlRequest.addParam(param: "session", value: sessionToken")

        return urlRequest
    }

    return urlRequest
}

I have a Router configured for the Paths but since I want my AuthHandler to be responsible to all Authentication related stuff I want to inject my sessionToken. This makes sure, together with RequestRetrier that any HTTP 401 related error is dealt with.

What is the best way to change the urlRequest?

Upvotes: 2

Views: 1159

Answers (2)

Coder ACJHP
Coder ACJHP

Reputation: 2194

Above solution not worked with me, i think because of my request method was post. Here is an example for who looking for update or remove parameters when retrying with post request.

Tested with Alamofire v5.9.1, iOS 12 ~ 17, Swift 5

func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {

    // get mutable copy
    var adaptedRequest = urlRequest
    
    // Convert body into string then update params
    if let httpBody = adaptedRequest.httpBody,
       let bodyString = String(data: httpBody, encoding: .utf8) {
        
        // Parse body params into dictionary
        var parameters = [String: String]()
        bodyString.split(separator: "&").forEach { pair in
            let keyValue = pair.split(separator: "=")
            if keyValue.count == 2 {
                parameters[String(keyValue[0])] = String(keyValue[1])
            }
        }

        // Update your params here
        parameters["key"] = "value"
        parameters["another_key"] = "another_value"

        // Convert back to httpBody
        let updatedBody = parameters.map { "\($0.key)=\($0.value)" }.joined(separator: "&")
        adaptedRequest.httpBody = updatedBody.data(using: .utf8)            

    }
    
    // Return the adapted request
    completion(.success(adaptedRequest))
}

Upvotes: 0

Sri
Sri

Reputation: 1336

Can you try

let params: Parameters = ["session": sessionToken]
return URLEncoding.default.encode(urlRequest, with: params)

(or)

return URLEncoding.queryString.encode(urlRequest, with: params)

Thanks Sriram

Upvotes: 7

Related Questions