Escaping URLs made simple

Screen Shot 2015-06-15 at 12.19.20 AM

How nice are the new URLQueryAllowedCharacterSet and stringByAddingPercentEncodingWithAllowedCharacters APIs? Very nice indeed. They enable you to instantly prepare queries by applying percent escaping to URL query components.

public func askWolfram(s : String) {
    let endpoint = "http://m.wolframalpha.com/input/?"
    if let item = ("i="+s).stringByAddingPercentEncodingWithAllowedCharacters(
        NSCharacterSet.URLQueryAllowedCharacterSet()) {
        let query = endpoint+item
        let request = NSURLRequest(URL: NSURL(string:query)!)
        wkview.loadRequest(request)
    }
}

Other new URL-specific character sets include support for legal URL fragments (the bit after the # symbol), host components, user names, passwords, and paths.

I think it’s finally time for me to put away my CFURLCreateStringByAddingPercentEscapes workarounds.

Comments are closed.