美文网首页
iOS 转码

iOS 转码

作者: BlessNeo | 来源:发表于2017-04-28 15:10 被阅读373次
  • 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
    }
}

参考:

相关文章

网友评论

      本文标题:iOS 转码

      本文链接:https://www.haomeiwen.com/subject/udpgzttx.html