URL Encoding a string [closed] URL Encoding a string [closed] json json

URL Encoding a string [closed]


Use This -

NSString *newCountryString = [country stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

This code will return a representation of the receiver using a given encoding to determine the percent escapes necessary to convert the receiver into a legal URL string.

for more details:https://developer.apple.com/documentation/foundation/nsstring/1415058-stringbyaddingpercentescapesusin

Edit - stringByAddingPercentEscapesUsingEncoding is deprecated in iOS 9. Use following instead

[country stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]

Swift 3 -

country.addingPercentEncoding( withAllowedCharacters: .urlHostAllowed)

for more details:https://developer.apple.com/documentation/foundation/nsstring/1411946-stringbyaddingpercentencodingwit?language=objc


As variant you can use method below:

- (NSString *)URLEncodeStringFromString:(NSString *)string{ static CFStringRef charset = CFSTR("!@#$%&*()+'\";:=,/?[] "); CFStringRef str = (__bridge CFStringRef)string; CFStringEncoding encoding = kCFStringEncodingUTF8; return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, str, NULL, charset, encoding));}


The NSSString method stringByAddingPercentEscapesUsingEncoding should help you. Also see How to prepare an NSURL from an NSString continaing international characters?