我收到一个json数据对象,然后从中提取一个字符串
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSString *country=jsonDictionary[@"address"][@"country"];
然后我尝试使该字符串适合在URL中使用
NSString *newCountryString = [country stringByReplacingOccurrencesOfString:@" "
withString:@"%%20"];
但它不起作用
如果我对newCountryString进行了硬编码,它将起作用,这是为什么呢?
用这个 -
NSString *newCountryString = [country stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
此代码将使用给定的编码返回接收者的表示形式,以确定将接收者转换为合法URL字符串所需的转义百分比。
有关更多详细信息:https : //developer.apple.com/documentation/foundation/nsstring/1415058-stringbyaddingpercentescapesusin
编辑-iOS 9中不推荐使用stringByAddingPercentEscapesUsingEncoding。
[country stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]
迅捷3-
country.addingPercentEncoding( withAllowedCharacters: .urlHostAllowed)
有关更多详细信息:https : //developer.apple.com/documentation/foundation/nsstring/1411946-stringbyaddingpercentencodingwitwit?language=objc
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句