URL编码字符串

时间:2014-01-28 10:40:13

标签: ios objective-c json url

我正在接收一个json数据对象,然后我从中提取一个字符串

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

然后我尝试使字符串适合在URL中使用

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

但它不起作用

如果我硬编码newCountryString它会起作用,为什么会这样?

4 个答案:

答案 0 :(得分:35)

使用此 -

NSString *newCountryString = [country stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

此代码将使用给定的编码返回接收器的表示,以确定将接收器转换为合法URL字符串所需的转义百分比。

了解更多详情: https://developer.apple.com/documentation/foundation/nsstring/1415058-stringbyaddingpercentescapesusin

修改 在iOS 9中不推荐使用stringByAddingPercentEscapesUsingEncoding。请改用以下内容

[country stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]

Swift 3 -

country.addingPercentEncoding( withAllowedCharacters: .urlHostAllowed)

了解更多详情: https://developer.apple.com/documentation/foundation/nsstring/1411946-stringbyaddingpercentencodingwit?language=objc

答案 1 :(得分:14)

作为变体,您可以使用以下方法:

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

答案 2 :(得分:0)

NSSString方法stringByAddingPercentEscapesUsingEncoding可以帮助您。另请参阅How to prepare an NSURL from an NSString continaing international characters?

答案 3 :(得分:-2)

我认为你应该删除一个%,如下所示

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

了解更多

NSMutableString stringByReplacingOccurrencesOfString Warning