web-dev-qa-db-fra.com

Comment faire l'encodage des paramètres dans Alamofire 4?

avoir du mal à comprendre le codage des paramètres dans Alamofire 4. Avant d'utiliser l'énumération ParameterEncoding et de faire quelque chose comme ceci:

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

Cependant, cela a depuis été remplacé par le ParameterEncodingprotocol:

public typealias Parameters = [String: Any]

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

Comment pourrais-je l'intégrer dans mon code actuel? Comment encoder mon mutableURLRequest actuel?

ÉDITER:

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)
    }

Lors d'une demande:

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
    }
13
KexAri

Vous pouvez faire une simple requête Alamofire comme celle-ci.

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


 })

Vous pouvez voir que j'ai utilisé JSONEncoding dans cette demande. Vous pouvez choisir votre mode d'encodage là-dedans parmi ceux-ci.

Dans JSONEncoding

  1. default

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

  2. prettyPrinted

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

Et dans URLEncoding

  1. défaut --

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

  2. methodDependent

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

  3. chaîne de requête

  4. httpBody

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

Et créez votre propre Custom Encoding Comme ceci.

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
    }
}

Et vous pouvez utiliser MyCusomEncoding dans vos Alamofire requêtes.

26
user6375148

Utilisez Alamofire.URLEncoding ()

Exemple de code:

// finalRequest: URLRequest? = nul

    do {
        try   finalRequest =  Alamofire.URLEncoding().encode(urlRequest as! URLRequestConvertible, with: parameters)
    } catch {
        //Handle error
    }
    return finalRequest!
4
SHISHIR R AMIN
do { 
    let alamofireRequest = try Alamofire.URLEncoding().encode(urlRequest as URLRequestConvertible, with: parameters)
    Alamofire.request(alamofireRequest).response { (dataResponse) in 

    }
} catch {

}
2
user