My book on iOS interface design, Design Teardowns: Step-by-step iOS interface design walkthroughs is now available!

Parsing query parameters

While working my new app Jibber, over the last couple of weeks, I needed to quickly parse a url and obtain the query parameters.

We could do this by breaking up the String representation of the url and creating a Dictionary. I've wrapped that up in a convenient extension to NSURL:

extension NSURL {  
    var queryDictionary: [String:String]? {
        if let query = self.query {
            var dict = [String:String]()
            for parameter in query.componentsSeparatedByString("&") {
                let components = parameter.componentsSeparatedByString("=")
                if components.count == 2 {
                    let key = components[0].stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
                    let value = components[1].stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
                    dict[key] = value
            return dict
        else {
            return nil

I built Jibber because debugging JSON requests in Xcode was infuriatingly painful. If you work with RESTful API, do check it out!