I have a URL string (NSString
) with spaces and &
characters. How do I url encode the entire string (including the &
ampersand
Use NSURLComponents to encode HTTP GET parameters:
var urlComponents = NSURLComponents(string: "https://www.google.de/maps/")!
urlComponents.queryItems = [
NSURLQueryItem(name: "q", value: String(51.500833)+","+String(-0.141944)),
NSURLQueryItem(name: "z", value: String(6))
]
urlComponents.URL // returns https://www.google.de/maps/?q=51.500833,-0.141944&z=6
http://www.ralfebert.de/snippets/ios/encoding-nsurl-get-parameters/
-(NSString *)encodeUrlString:(NSString *)string {
return CFBridgingRelease(
CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)string,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]"),
kCFStringEncodingUTF8)
);
}
according to the following blog
swift code based on chown's objc answer in this thread.
extension String {
func urlEncode() -> String {
return CFURLCreateStringByAddingPercentEscapes(
nil,
self,
nil,
"!*'();:@&=+$,/?%#[]",
CFStringBuiltInEncodings.UTF8.rawValue
)
}
}
//This is without test
NSMutableCharacterSet* set = [[NSCharacterSet alphanumericCharacterSet] mutableCopy];
[set addCharactersInString:@"-_.~"];
NSString *encode = [test stringByAddingPercentEncodingWithAllowedCharacters:set];
I faced a similar problem passing complex strings as a POST parameter. My strings can contain Asian characters, spaces, quotes and all sorts of special characters. The solution I eventually found was to convert my string into the matching series of unicodes, e.g. "Hu0040Hu0020Hu03f5...." using [NSString stringWithFormat:@"Hu%04x",[string characterAtIndex:i]] to get the Unicode from each character in the original string. The same can be done in Java.
This string can be safely passed as a POST parameter.
On the server side (PHP), I change all the "H" to "\" and I pass the resulting string to json_decode. Final step is to escape single quotes before storing the string into MySQL.
This way I can store any UTF8 string on my server.
In Swift 3, please try out below:
let stringURL = "YOUR URL TO BE ENCODE";
let encodedURLString = stringURL.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(encodedURLString)
Since, stringByAddingPercentEscapesUsingEncoding
encodes non URL characters but leaves the reserved characters (like !*'();:@&=+$,/?%#[]
), You can encode the url like the following code:
let stringURL = "YOUR URL TO BE ENCODE";
let characterSetTobeAllowed = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)
if let encodedURLString = stringURL.addingPercentEncoding(withAllowedCharacters: characterSetTobeAllowed) {
print(encodedURLString)
}