如何在Alamofire 4中进行参数编码?

时间:2021-07-17 22:48:48

having trouble getting my head around parameter encoding in Alamofire 4. Before I would use the ParameterEncoding enumeration and do something like this:

在Alamofire 4中,我在参数编码方面遇到了麻烦。在使用参数编码枚举之前,先做如下操作:

Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0

However this has since been replaced with the ParameterEncoding protocol:

然而,此后这已被参数编码协议所取代:

public typealias Parameters = [String: Any]

public protocol ParameterEncoding {
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
}

How could I intergrate this into my current code? How do I encode my current mutableURLRequest?

我如何将它整合到我当前的代码中呢?如何对当前的mutableURLRequest进行编码?

EDIT:

编辑:

static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, Any>, data:Data?, contentType: ContentType, parameterName: String) -> (URLRequestConvertible, Data) {

        var urlRequest = URLRequest(url: URL(string: urlString)!)
        urlRequest.cachePolicy = .reloadIgnoringLocalCacheData
        urlRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue
        let boundaryConstant = "multipart-boundary";
        let multipartContentType = "multipart/form-data;boundary="+boundaryConstant
        urlRequest.setValue(multipartContentType, forHTTPHeaderField: "Content-Type")

        // Create upload data to send
        var uploadData = Data()

        if data != nil {
            // Add multipart data
            uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
            if contentType == .Image_JPEG {
                uploadData.append("Content-Disposition: form-data; name=\"\(parameterName)\"; filename=\"file.jpeg\"\r\n".data(using: String.Encoding.utf8)!)
                uploadData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
            } else if contentType == .Audio {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "MMyyyyddsshhmmA" // superset of OP's format
                let audioFileName = "recording-\(dateFormatter.string(from: Date())).mp4"
                uploadData.append("Content-Disposition: form-data; name=\"\(parameterName)\"; filename=\"\(audioFileName)\"\r\n".data(using: String.Encoding.utf8)!)
                uploadData.append("Content-Type: audio/mpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
            }
            uploadData.append(data!)
        }

        // Add parameters
        for (key, value) in parameters {
            uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
            uploadData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!)
        }
        uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!)

        // return URLRequestConvertible and Data
        return (urlRequest, uploadData)
    }

When doing a request:

在一个请求:

let urlRequest = urlRequestWithComponents(urlString: url, parameters: parameters, data: imageData, contentType: .Image_JPEG, parameterName: "question_img")


    alamoManager.upload(urlRequest.1, with: urlRequest.0).responseObject { (response: DataResponse<CustomResponse>) in

     //Some code
    }

3 个解决方案

#1


18  

You can do a simple Alamofire request like this.

您可以像这样做一个简单的Alamofire请求。

import Alamofire
import AlamofireObjectMapper
import ObjectMapper

//
//

Alamofire.request("hello.com", method: .post, parameters: ["name": "alvin"], encoding: JSONEncoding.default, headers: nil).responseObject(completionHandler: { (response : DataResponse<YourModelHere>) in


 })

You can see that I have used JSONEncoding in this request. You can choose your way of encoding in there from any of these.

您可以看到,我在这个请求中使用了JSONEncoding。你可以从这些编码中选择你的编码方式。

In JSONEncoding

在JSONEncoding

  1. default

    默认的

    Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)

    请求(“https://httpbin.org/post”,方法:。post,参数:参数,编码:JSONEncoding.default)

  2. prettyPrinted

    prettyPrinted

    Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding. prettyPrinted)

    请求(“https://httpbin.org/post”,方法:。post,参数:参数:参数,编码:jsoncoding。prettyPrinted)

And in URLEncoding

而在URLEncoding

  1. default --

    默认的,

    Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default)

    请求(“https://httpbin.org/get”,参数:参数,编码:URLEncoding.default)

  2. methodDependent

    methodDependent

    Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent))

    请求(“https://httpbin.org/get”,参数:参数,编码:URLEncoding(目标:。methoddependent))

  3. queryString

    变量的名称

  4. httpBody

    httpBody

    Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody)

    请求(“https://httpbin.org/post”,参数:参数,编码:URLEncoding.httpBody)

And create your own Custom Encoding like this.

然后创建自己的自定义编码。

public struct MyCusomEncoding: ParameterEncoding {

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {

        var urlRequest = try urlRequest.asURLRequest()

        guard let parameters = parameters else { return urlRequest }

        do {

            let data = //

            // Do your custom stuff here, convert your parameters it into JSON, String, Something else or may be encrypted...

        urlRequest.httpBody = data

        } catch {
            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
        }

        return urlRequest
    }
}

And you can use MyCusomEncoding in your Alamofire requests.

你可以在你的请求中使用MyCusomEncoding。

#2


4  

Use Alamofire.URLEncoding()

使用Alamofire.URLEncoding()

Code Example:

代码示例:

//finalRequest:URLRequest? = nil

/ / finalRequest:URLRequest ?= nil

    do {
        try   finalRequest =  Alamofire.URLEncoding().encode(urlRequest as! URLRequestConvertible, with: parameters)
    } catch {
        //Handle error
    }
    return finalRequest!

#3


0  

do { 
    let alamofireRequest = try Alamofire.URLEncoding().encode(urlRequest as URLRequestConvertible, with: parameters)
    Alamofire.request(alamofireRequest).response { (dataResponse) in 

    }
} catch {

}

#1


18  

You can do a simple Alamofire request like this.

您可以像这样做一个简单的Alamofire请求。

import Alamofire
import AlamofireObjectMapper
import ObjectMapper

//
//

Alamofire.request("hello.com", method: .post, parameters: ["name": "alvin"], encoding: JSONEncoding.default, headers: nil).responseObject(completionHandler: { (response : DataResponse<YourModelHere>) in


 })

You can see that I have used JSONEncoding in this request. You can choose your way of encoding in there from any of these.

您可以看到,我在这个请求中使用了JSONEncoding。你可以从这些编码中选择你的编码方式。

In JSONEncoding

在JSONEncoding

  1. default

    默认的

    Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)

    请求(“https://httpbin.org/post”,方法:。post,参数:参数,编码:JSONEncoding.default)

  2. prettyPrinted

    prettyPrinted

    Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding. prettyPrinted)

    请求(“https://httpbin.org/post”,方法:。post,参数:参数:参数,编码:jsoncoding。prettyPrinted)

And in URLEncoding

而在URLEncoding

  1. default --

    默认的,

    Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default)

    请求(“https://httpbin.org/get”,参数:参数,编码:URLEncoding.default)

  2. methodDependent

    methodDependent

    Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent))

    请求(“https://httpbin.org/get”,参数:参数,编码:URLEncoding(目标:。methoddependent))

  3. queryString

    变量的名称

  4. httpBody

    httpBody

    Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody)

    请求(“https://httpbin.org/post”,参数:参数,编码:URLEncoding.httpBody)

And create your own Custom Encoding like this.

然后创建自己的自定义编码。

public struct MyCusomEncoding: ParameterEncoding {

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {

        var urlRequest = try urlRequest.asURLRequest()

        guard let parameters = parameters else { return urlRequest }

        do {

            let data = //

            // Do your custom stuff here, convert your parameters it into JSON, String, Something else or may be encrypted...

        urlRequest.httpBody = data

        } catch {
            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
        }

        return urlRequest
    }
}

And you can use MyCusomEncoding in your Alamofire requests.

你可以在你的请求中使用MyCusomEncoding。

#2


4  

Use Alamofire.URLEncoding()

使用Alamofire.URLEncoding()

Code Example:

代码示例:

//finalRequest:URLRequest? = nil

/ / finalRequest:URLRequest ?= nil

    do {
        try   finalRequest =  Alamofire.URLEncoding().encode(urlRequest as! URLRequestConvertible, with: parameters)
    } catch {
        //Handle error
    }
    return finalRequest!

#3


0  

do { 
    let alamofireRequest = try Alamofire.URLEncoding().encode(urlRequest as URLRequestConvertible, with: parameters)
    Alamofire.request(alamofireRequest).response { (dataResponse) in 

    }
} catch {

}