URL decode in iOS

IosSwiftUrldecode

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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
    }
}

Solution 2 - Ios

Swift 2 and later (Xcode 7)

var s = "aa bb -[:/?&=;+!@#$()',*]";

let sEncode = s.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

let sDecode = sEncode?.stringByRemovingPercentEncoding

Solution 3 - Ios

The stringByReplacingEscapesUsingEncoding method is behaving correctly. The "+" character is not part of percent-encoding. This server is using it incorrectly; it should be using a percent-escaped space here (%20). If, for a particular response, you want spaces where you see "+" characters, you just have to work around the server behavior by performing the substitution yourself, as you are already doing.

Solution 4 - Ios

You only need:

print("Decode: ", yourUrlAsString.removingPercentEncoding) 

Solution 5 - Ios

It's better to use built-in URLComponents struct, since it follows proper guidelines.

extension URL
{
    var parameters: [String: String?]?
    {
        if  let components = URLComponents(url: self, resolvingAgainstBaseURL: false), 
            let queryItems = components.queryItems
        {
            var parameters = [String: String?]()
            for item in queryItems {
                parameters[item.name] = item.value
            }
            return parameters
        } else {
            return nil
        }
    }
}

Solution 6 - Ios

In my case, I NEED a plus ("+") signal in a phone number in parameters of a query string, like "+55 11 99999-5555". After I discovered that the swift3 (xcode 8.2) encoder don't encode "+" as plus signal, but space, I had to appeal to a workaround after the encode:

Swift 3.0

_strURL = _strURL.replacingOccurrences(of: "+", with: "%2B")

Solution 7 - Ios

In Swift 3

extension URL {
    var parseQueryString: [String: String] {
        var results = [String: String]()
        
        if let pairs = self.query?.components(separatedBy: "&"),  pairs.count > 0 {
            for pair: String in pairs {
                if let keyValue = pair.components(separatedBy: "=") as [String]? {
                    results.updateValue(keyValue[1], forKey: keyValue[0])
                }
            }
        }
        return results
    }
}

in your code to access below

let parse = url.parseQueryString
        print("parse \(parse)" )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJibWView Question on Stackoverflow
Solution 1 - IosVyacheslavView Answer on Stackoverflow
Solution 2 - Ios米米米View Answer on Stackoverflow
Solution 3 - IosmattView Answer on Stackoverflow
Solution 4 - IosScottyBladesView Answer on Stackoverflow
Solution 5 - IosnikansView Answer on Stackoverflow
Solution 6 - IosCaiçaraView Answer on Stackoverflow
Solution 7 - IosAmul4608View Answer on Stackoverflow