如何检测已编码的NSString
。?
我正在编码我的字符串,如下所示。在编码之前,我只想验证此[product url]
已编码的天气。
NSString *encodedUrlString=[[product url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
答案 0 :(得分:7)
您可以尝试解码字符串,看看原始字符串和解码后的字符串是否相同。如果它们相同则尚未编码。
NSString *original = product.url;
NSString *decoded = [original stringByReplacingPercentEscapesUsingEncoding:NSUTF8Encoding];
if ([original isEqualToString:decoded]) {
// The URL was not encoded yet
NSString *encodedUrlString=[[product url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
} else {
// The URL was already encoded
}
BTW - 从iOS 9开始,这些方法已被弃用,因此,如果您的应用的部署目标是iOS 9.0或更高版本,则应使用较新的方法。
对于iOS 9或更高版本,您应该使用:
NSString *original = product.url;
NSString *decoded = [original stringByRemovingPercentEncoding];
if ([original isEqualToString:decoded]) {
// The URL was not encoded yet
NSString *encodedUrlString=[[product url] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
} else {
// The URL was already encoded
}