Sample code for 30+ languages & platforms
Swift

URL Encoding and Decoding

See more Encryption Examples

Demonstrates URL encoding and decoding.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // To URL encoding a string:
    var s: String? = "Why a > b?"

    let sb = CkoStringBuilder()!
    success = sb.append(value: s)

    // URL encode the string.
    sb.encode(encoding: "url", charset: "utf-8")

    // Show the URL encoded string:
    var sEncoded: String? = sb.getAsString()
    print("\(sEncoded!)")

    // The result is:  Why%20a%20%3E%20b%3F

    // If you prefer "+" instead of "%20" for SPACE chars:
    var numReplaced: Int = sb.replace(value: "%20", replacement: "+").intValue
    print("\(sb.getAsString()!)")

    // Output is:   Why+a+%3E+b%3F

    // To decode:
    sb.decode(encoding: "url", charset: "utf-8")
    print("\(sb.getAsString()!)")

    // Result is: Why a > b?

}