iOS 转码

  • URLEncode

iOS 开发中请求访问 Http(s) 时,必须对 URL 进行转码 (Encode),如果是后台 App 接口,通常会使用第三方网络框架 AFNetworing,转码工作不需要我们关心,AFNetworing已经帮我们处理了。具体的类是在Serialization文件夹下的AFURLRequestSerialization,主要的方法摘录如下:

AFNetworking version 3.1.0

AFURLRequestSerialization.h

/**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
@param string The string to be percent-escaped.
@return The percent-escaped string.
*/
FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
/**
A helper method to generate encoded url query parameters for appending to the end of a URL.
@param parameters A dictionary of key/values to be encoded.
@return A url encoded query string
*/
FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters);

AFURLRequestSerialization.m

 /**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
   - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
   - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
   - parameter string: The string to be percent-escaped.
   - returns: The percent-escaped string.
*/
NSString * AFPercentEscapedStringFromString(NSString *string) {
   static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
   static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
   NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
   [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
   // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028
   // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
   static NSUInteger const batchSize = 50;
   NSUInteger index = 0;
   NSMutableString *escaped = @"".mutableCopy;
   while (index < string.length) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wgnu"
       NSUInteger length = MIN(string.length - index, batchSize);
#pragma GCC diagnostic pop
       NSRange range = NSMakeRange(index, length);
       // To avoid breaking up character sequences such as 👴🏻👮🏽
       range = [string rangeOfComposedCharacterSequencesForRange:range];
       NSString *substring = [string substringWithRange:range];
       NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
       [escaped appendString:encoded];
       index += range.length;
   }
   return escaped;
}
#pragma mark -
FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
   NSMutableArray *mutablePairs = [NSMutableArray array];
   for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
       [mutablePairs addObject:[pair URLEncodedStringValue]];
   }
   return [mutablePairs componentsJoinedByString:@"&"];
}
NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
   return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
}
NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
   NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
   NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
   if ([value isKindOfClass:[NSDictionary class]]) {
       NSDictionary *dictionary = value;
       // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
       for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
           id nestedValue = dictionary[nestedKey];
           if (nestedValue) {
               [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
           }
       }
   } else if ([value isKindOfClass:[NSArray class]]) {
       NSArray *array = value;
       for (id nestedValue in array) {
           [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
       }
   } else if ([value isKindOfClass:[NSSet class]]) {
       NSSet *set = value;
       for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
           [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)];
       }
   } else {
       [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
   }
   return mutableQueryStringComponents;
}

在实际的开发过程中,也会碰到需要我们手动进行 URL Encode 的情况,用到的方法很多都是网上这两种方法:

/******************  转码  *********************/
//NSString to UTF8String
+ (NSString *)UTF8String:(NSString *)tempString
{
   return [originalStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

+ (NSString *)urlEncode:(NSString *)originalStr
{
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes 
(kCFAllocatorDefault,
 (CFStringRef)tempString, 
NULL,
 (CFStringRef)@"!*'();:@&=+ $,./?%#[]", kCFStringEncodingUTF8));
}

然而关键的两个方法stringByAddingPercentEscapesUsingEncoding:CFURLCreateStringByAddingPercentEscapes在 iOS9 已经淘汰过时了。

Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.

其实在 iOS7 已经有了替换的方法:stringByAddingPercentEncodingWithAllowedCharacters:
其中在 URL Encode 时相关的NSCharacterSet有下列选项,但是后面列出的 Character 并没有包含在对应的 set 中。

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

所以使用以下方法做 URL Encode 还是不够的

NSString *URLEscapedString =
[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

回头看AFNetWorking中的方法就明白了:只需要将这些特殊符号加入到 set 中就可以了

static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
NSString *URLEscapedString =
[string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];

当然你把? /也转码也不会有问题。
Swift:

extension String {
    // URL Decode
    func URLDecode() -> String? {
        return self.stringByRemovingPercentEncoding // `stringByReplacingPercentEscapesUsingEncoding` is deprecated
    }

    // URL Encode
    func URLEncode() -> String? {
        return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString: "!*'\"();:@&=+$,/?%#[]% ").invertedSet) // `CFURLCreateStringByAddingPercentEscapes` is deprecated
    }
}

参考:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,053评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,527评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,779评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,685评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,699评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,609评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,989评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,654评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,890评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,634评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,716评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,394评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,976评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,950评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,191评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,849评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,458评论 2 342

推荐阅读更多精彩内容