FormURLEncoder

open class FormURLEncoder

The FormURLEncoder class encodes any Encodable instance into the application/x-www-form-urlencoded Content-Type.

The example below shows how to encode an instance of a simple GroceryProduct type to a form URL encoded string. The type adopts Codable so that it’s encodable as JSON using a JSONEncoder instance.

struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}

let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")

let encoder = FormURLEncoder()
let results = try encoder.stringEncode(pear)
print(results)

/* Prints:
 description=A%20ripe%20pear.&name=Pear&points=250
*/
  • The strategy used when encoding dates.

    Declaration

    Swift

    open var dateEncodingStrategy: JSONEncoder.DateEncodingStrategy
  • Creates a new, reusable Form URL encoder with the default date encoding strategy.

    Declaration

    Swift

    public init()
  • Encodes an Encodable type to the form URL format represented as Data.

    Throws

    An EncodingError can be thrown.

    Declaration

    Swift

    open func encode<T>(_ value: T, percentEncoded: Bool = true) throws -> Data where T : Encodable

    Parameters

    value

    The Encodable instance to encode.

    percentEncoded

    A boolean indicating if the resulting encoding should contain percent encoding.

    Return Value

    A Data instance of the formatted data.

  • Encodes an Encodable type to the form URL format represented as a String.

    Throws

    An EncodingError can be thrown.

    Declaration

    Swift

    open func stringEncode<T>(_ value: T, percentEncoded: Bool = true) throws -> String where T : Encodable

    Parameters

    value

    The Encodable instance to encode.

    percentEncoded

    A boolean indicating if the resulting encoding should contain percent encoding.

    Return Value

    A String instance.

  • Encodes an Encodable type to the form URL format represented as an array of URLQueryItem instances.

    Throws

    An EncodingError can be thrown.

    Declaration

    Swift

    open func queryItemEncode<T>(_ value: T) throws -> [URLQueryItem] where T : Encodable

    Parameters

    value

    The Encodable instance to encode.

    Return Value

    An array of URLQueryItem instances.