URL decode in iOS

JibW picture JibW · Oct 6, 2015 · Viewed 40.5k times · Source

I am using Swift 1.2 to develop my iPhone application and I am communicating with a http web service.

The response I am getting is in query string format (key-value pairs) and URL encoded in .Net.

I can get the response, but looking the proper way to decode using Swift.

Sample response is as follows

status=1&message=The+transaction+for+GBP+12.50+was+successful

Tried following way to decode and get the server response

// This provides encoded response String
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
var decodedResponse = responseString.stringByReplacingEscapesUsingEncoding(NSUTF8StringEncoding)!

How can I replace all URL escaped characters in the string?

Answer

Vyacheslav picture Vyacheslav · Sep 14, 2016

To encode and decode urls create this extention somewhere in the project:

Swift 2.0

extension String
{   
    func encodeUrl() -> String
    {
        return self.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())
    }
func decodeUrl() -> String
    {
        return self.stringByRemovingPercentEncoding
    }

}

Swift 3.0

 extension String
    {   
        func encodeUrl() -> String
        {
            return self.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed())
        }
    func decodeUrl() -> String
        {
            return self.removingPercentEncoding
        }

    }

Swift 4.1

extension String
{
    func encodeUrl() -> String?
    {
        return self.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
    }
    func decodeUrl() -> String?
    {
        return self.removingPercentEncoding
    }
}