ixany ixany - 1 month ago 19
Swift Question

How to create a custom NSCharacterSet?

I'm using

NSCharacterSet.URLQueryAllowedCharacterSet()
to add percent-encoding on a string, however, it seems to be blind for some chars, i.e. "&" or "?". How can I build a custom NSCharacterSet based on the existing one?

Answer

The most typical way to create a new character set is using + characterSetWithCharactersInString, giving a NSString 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("?&")

For URL encoding, also note Objective-C url encoding

Comments