Alamofire 3 Custom Encoding To Alamofire 4 Custom Encoding

后端 未结 3 1753
天命终不由人
天命终不由人 2021-02-15 23:16

I have method writing in Alamofire 3 with customParameterEncoding. This custom encoding just replaces \"[]=\" with \"=\" in queryString and returns it.

Alamofire         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-15 23:47

    Just separating structs for GET and POST also works.

    http://matsue.github.io/post/how-to-remove-square-brackets-with-alamofire/

    Alamofire 4 with Swift 3

    // Remove square brackets for GET request
    struct CustomGetEncoding: ParameterEncoding {
        func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
            var request = try URLEncoding().encode(urlRequest, with: parameters)
            request.url = URL(string: request.url!.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "="))
            return request
        }
    }
    
    // Remove square brackets for POST request
    struct CustomPostEncoding: ParameterEncoding {
        func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
            var request = try URLEncoding().encode(urlRequest, with: parameters)
            let httpBody = NSString(data: request.httpBody!, encoding: String.Encoding.utf8.rawValue)!
            request.httpBody = httpBody.replacingOccurrences(of: "%5B%5D=", with: "=").data(using: .utf8)
            return request
        }
    }
    
    // Use structs for requests 
    Alamofire.request("http://example.com", method: .get, parameters: ["foo": ["bar1", "bar2"]], encoding: CustomGetEncoding())
    Alamofire.request("http://example.com", method: .post, parameters: ["foo": ["bar1", "bar2"]], encoding: CustomPostEncoding())
    

提交回复
热议问题