我有一个NSString带有空格和&字符的 URL 字符串 ( )。如何对整个字符串(包括&& 字符和空格)进行 url 编码?
NSString
&
不幸的是,stringByAddingPercentEscapesUsingEncoding并不总是 100% 有效。它对非 URL 字符进行编码,但保留保留字符(如斜杠/和 & 符号&)单独存在。显然这是苹果知道的一个 错误 ,但由于他们还没有修复它,我一直在使用这个类别对字符串进行 url 编码:
stringByAddingPercentEscapesUsingEncoding
/
@implementation NSString (NSString_Extended) - (NSString *)urlencode { NSMutableString *output = [NSMutableString string]; const unsigned char *source = (const unsigned char *)[self UTF8String]; int sourceLen = strlen((const char *)source); for (int i = 0; i < sourceLen; ++i) { const unsigned char thisChar = source[i]; if (thisChar == ' '){ [output appendString:@"+"]; } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || (thisChar >= 'a' && thisChar <= 'z') || (thisChar >= 'A' && thisChar <= 'Z') || (thisChar >= '0' && thisChar <= '9')) { [output appendFormat:@"%c", thisChar]; } else { [output appendFormat:@"%%%02X", thisChar]; } } return output; }
像这样使用:
NSString *urlEncodedString = [@"SOME_URL_GOES_HERE" urlencode]; // Or, with an already existing string: NSString *someUrlString = @"someURL"; NSString *encodedUrlStr = [someUrlString urlencode];
这也有效:
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)unencodedString, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );