URL Encoding a string
ios, json, objective-c, url
Solution
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
Problem
i am receiving a json data object and then i extract a string from it ``` NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSString *country=jsonDictionary[@"address"][@"country"]; ``` then i try to make the string suitable to be used in a URL ``` NSString *newCountryString = [country stringByReplacingOccurrencesOfString:@" " withString:@"%%20"]; ``` but it is not working if i hard coded the newCountryString it would work, why is that ?