Created
August 21, 2019 10:40
-
-
Save akhtarraza/a9b98179666432b3f9e9a7fe328d6247 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Alamofire | |
private let kArrayElementKey = "arrayElementKey" | |
extension Array { | |
func asParameter() -> Parameters { | |
return [kArrayElementKey: self] | |
} | |
} | |
/// Convert the parameters into a json array, and it is added as the request body. | |
/// The array must be sent as parameters using its `asParameters` method. | |
public struct ArrayEncoding: ParameterEncoding { | |
/// The options for writing the parameters as JSON data. | |
public let options: JSONSerialization.WritingOptions | |
/// Creates a new instance of the encoding using the given options | |
/// | |
/// - parameter options: The options used to encode the json. Default is `[]` | |
/// | |
/// - returns: The new instance | |
public init(options: JSONSerialization.WritingOptions = []) { | |
self.options = options | |
} | |
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { | |
var urlRequest = try urlRequest.asURLRequest() | |
guard let parameters = parameters, let array = parameters[kArrayElementKey] else { | |
return urlRequest | |
} | |
do { | |
let data = try JSONSerialization.data(withJSONObject: array, options: options) | |
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { | |
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") | |
} | |
urlRequest.httpBody = data | |
} catch { | |
throw AFError.parameterEncodingFailed(reason: AFError.ParameterEncodingFailureReason.jsonEncodingFailed(error: error)) | |
} | |
return urlRequest | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment