I’m using CharacterSet.urlQueryAllowed
to add percent-encoding to a String.
Some characters are not encoded the way I expected (i.e. &
and ?
are not changed). That being said, I had the idea to build a custom CharacterSet
, ideally based on an existing one.
What’s the best approach to do so?
Examples of character sets include International EBCDIC, Latin 1, and Unicode. Character sets are chosen on the basis of the letters and symbols required. Character sets are referred to by a name or by an integer identifier called the coded character set identifier (CCSID).
CharacterSet (and its reference type counterpart, NSCharacterSet ) is a Foundation type used to trim, filter, and search for characters in text. In Swift, a Character is an extended grapheme cluster (really just a String with a length of 1) that comprises one or more scalar values.
The most typical way to create a new character set is using
CharacterSet(charactersIn:)
, giving a String
with all the characters of the set.
Adding some characters to an existing set can be achieved using:
let characterSet = NSMutableCharacterSet() //create an empty mutable set
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLQueryAllowedCharacterSet())
characterSet.addCharactersInString("?&")
or in Swift 3+ simply:
var characterSet = CharacterSet.urlQueryAllowed
characterSet.insert(charactersIn: "?&")
For URL encoding, also note Objective-C and Swift URL encoding
You can try my method:
let password = "?+=!@#$%^&*()-_abcdABCD1234`~"
// Swift 2.3
extension NSCharacterSet {
static var rfc3986Unreserved: NSCharacterSet {
let mutable = NSMutableCharacterSet()
mutable.formUnionWithCharacterSet(.alphanumericCharacterSet())
mutable.addCharactersInString("-_.~")
return mutable
}
}
let encoding = password.stringByAddingPercentEncodingWithAllowedCharacters(.rfc3986Unreserved)
// Swift 3
extension CharacterSet {
static var rfc3986Unreserved: CharacterSet {
return CharacterSet(charactersIn: "-_.~").union(.alphanumerics)
}
}
let encoding = password.addingPercentEncoding(withAllowedCharacters: .rfc3986Unreserved)
Print:
original -> ?+=!@#$%^&*()-_abcdABCD1234`~
encoding -> %3F%2B%3D%21%40%23%24%25%5E%26%2A%28%29-_abcdABCD1234%60~
rfc3986: https://www.rfc-editor.org/rfc/rfc3986
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With