URL编码一个string

我收到一个json数据对象,然后从中提取一个string

NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSString *country=jsonDictionary[@"address"][@"country"]; 

然后我尝试使该string适合在URL中使用

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

但它不工作

如果我硬编码newCountryString它会工作,为什么呢?

用这个 –

 NSString *newCountryString = [country stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

此代码将使用给定的编码返回接收方的表示forms,以确定将接收方转换为合法的URLstring所需的百分比转义。

有关更多详细信息: https : //developer.apple.com/documentation/foundation/nsstring/1415058-stringbyaddingpercentescapesusin

编辑 – stringByAddingPercentEscapesUsingEncoding已被弃用在iOS 9中

 [country stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]] 

Swift 3 –

 country.addingPercentEncoding( withAllowedCharacters: .urlHostAllowed) 

有关更多详细信息: https : //developer.apple.com/documentation/foundation/nsstring/1411946-stringbyaddingpercentencodingwit?language = bjc

作为变体,你可以使用下面的方法:

 - (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)); } 

NSString方法stringByAddingPercentEscapesUsingEncoding应该可以帮到你。 另请参阅如何从NSString国际字符准备NSURL?

我认为你应该删除一个像下面这样的%

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

为更多

NSMutableString stringByReplacingOccurrencesOfString警告