检查NSString是否被编码 [英] Check NSString is encoded or not

查看:194
本文介绍了检查NSString是否被编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测已编码的 NSString

我正在编码我的字符串如下。在编码之前,我只想验证天气,这个 [product url] 已经被编码了。

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];


推荐答案

您可以尝试解码字符串,字符串和解码的字符串是否相同。如果它们相同,那么它还没有编码。

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 - 这些方法与iOS 9不同,所以如果您的应用的部署目标是iOS 9.0或更高版本,您应该使用较新的方法。

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.

对于iOS 9或更高版本你应该使用:

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
}

这篇关于检查NSString是否被编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆