问题
How to detect a NSString which is already encoded or not.?
I'm encoding my string like below. Before encoding this i just want to verify weather this [product url] is already encoded or not.
NSString *encodedUrlString=[[product url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
回答1:
You could try decoding the string and see if the original string and the decoded string are the same or not. If they are the same then it wasn't encoded yet.
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 - these methods are deprecated as of iOS 9 so if your app's Deployment Target is iOS 9.0 or later you should use the newer methods.
For iOS 9 or later you should use:
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
}
来源:https://stackoverflow.com/questions/33445003/check-nsstring-is-encoded-or-not