URL decode in iOS
Solution 1:
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:
Swift 2 and later (Xcode 7)
var s = "aa bb -[:/?&=;+!@#$()',*]";
let sEncode = s.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
let sDecode = sEncode?.stringByRemovingPercentEncoding
Solution 3:
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:
You only need:
print("Decode: ", yourUrlAsString.removingPercentEncoding)
Solution 5:
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
}
}
}