URL Encoding a string [closed]

2019-01-18 21:04发布

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 ?

4条回答
一纸荒年 Trace。
2楼-- · 2019-01-18 21:26

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

查看更多
仙女界的扛把子
3楼-- · 2019-01-18 21:32

I think you should remove one % like below

NSString *newCountryString = [country stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

for more

NSMutableString stringByReplacingOccurrencesOfString Warning

查看更多
贼婆χ
4楼-- · 2019-01-18 21:33

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));
}
查看更多
可以哭但决不认输i
5楼-- · 2019-01-18 21:47

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

查看更多
登录 后发表回答