Check NSString is encoded or not

两盒软妹~` 提交于 2019-12-08 13:56:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!