ios - 如何对字符串进行 URL 编码

我有一个带有空格和 & 字符的 URL 字符串 (NSString)。如何对整个字符串进行 url 编码(包括 & 和号字符和空格)?

最佳答案

不幸的是,stringByAddingPercentEscapesUsingEncoding 并不总是 100% 有效。它对非 URL 字符进行编码,但保留保留字符(如斜线 / 和 & 符号 &)单独。显然这是 Apple 知道的一个 错误,但由于他们还没有修复它,我一直在使用这个类别对字符串进行 url 编码:

@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 );

一些关于这个主题的好读物:

Objective-c iPhone percent encode a string?
Objective-C and Swift URL encoding

http://cybersam.com/programming/proper-url-percent-encoding-in-ios
https://devforums.apple.com/message/15674#15674 http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/

https://stackoverflow.com/questions/8088473/

相关文章:

objective-c - 在 Objective-C 中将 NSArray 转换为 NSStrin

ios - UICollectionView 中的单元格间距

ios - UITableViewCell 显示白色背景,在 iOS7 上无法修改

ios - 如何更改 UIButton 标题颜色?

iphone - 如何在 Objective-C 中定义和使用 ENUM?

iphone - @try - Objective-C 中的 catch block

objective-c - 禁用某些文件的自动引用计数

objective-c - Xcode 5 中提供了哪些新的文档命令?

objective-c - 在 Objective-C 中转换为绝对值

objective-c - 在 Objective-C 中,Java 的 "instanceof"关