Skip to content

Instantly share code, notes, and snippets.

@mkujalowicz
Last active September 27, 2016 16:23
Show Gist options
  • Save mkujalowicz/3903fd7efd695864eca606ccc12e097e to your computer and use it in GitHub Desktop.
Save mkujalowicz/3903fd7efd695864eca606ccc12e097e to your computer and use it in GitHub Desktop.
Swift playground for testing standard iOS URL encoding methods
//: Playground - noun: a place where people can play
import UIKit
extension Dictionary where Key: ExpressibleByStringLiteral, Value: ExpressibleByStringLiteral {
var queryItems: [URLQueryItem] {
return map {
return URLQueryItem(name: String(describing: $0), value: String(describing: $1))
}
}
func encodedFormDataWithAllowedCharacters(_ characterSet: CharacterSet) -> String {
return (map {
let name = String(describing: $0).addingPercentEncoding(withAllowedCharacters: characterSet)!
let value = String(describing: $1).addingPercentEncoding(withAllowedCharacters: characterSet)!
return name + "=" + value
} as [String]).joined(separator: "&")
}
}
extension CharacterSet {
func ASCIICharacters() -> String {
guard hasMember(inPlane: 0) else {
return ""
}
// ASCII characters are in plane 0 (BMP) in range 0...7f
return Array(0...0x7f).filter() {
return contains(UnicodeScalar($0))
}.map() {
return Character(UnicodeScalar($0))
}.reduce("") {
return $0 + "\($1)"
}
}
static func customURLQueryAllowedCharacterSet() -> CharacterSet {
return CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.-*_")
}
}
func testEncoding(
queryDictionary: [String: String],
correctlyEncodedValue: String) -> (iOS8: Bool, iOS7: Bool, custom: Bool) {
// iOS8+ method
var urlComponents = URLComponents()
urlComponents.queryItems = queryDictionary.queryItems
let ios8 = urlComponents.percentEncodedQuery! == correctlyEncodedValue
// iOS7 method
let ios7 = queryDictionary.encodedFormDataWithAllowedCharacters(
CharacterSet.urlQueryAllowed) == correctlyEncodedValue
// Custom method
let custom = queryDictionary.encodedFormDataWithAllowedCharacters(
CharacterSet.customURLQueryAllowedCharacterSet()) == correctlyEncodedValue
return (iOS8: ios8, iOS7: ios7, custom: custom)
}
testEncoding(queryDictionary: ["name": "value+value"], correctlyEncodedValue: "name=value%2Bvalue")
testEncoding(queryDictionary: ["name": "~!@#$%^&*()__{}\":|+?><,.//;'qow"],
correctlyEncodedValue: "name=%7E%21%40%23%24%25%5E%26*%28%29__%7B%7D%22%3A%7C%2B%3F%3E%3C%2C.%2F%2F%3B%27qow")
// Allowed characters
CharacterSet.urlQueryAllowed.ASCIICharacters()
CharacterSet.customURLQueryAllowedCharacterSet().ASCIICharacters()
@mkujalowicz
Copy link
Author

updated to Swift 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment