iOS 9以后Url连接的NSUTF8StringEncoding转码实现

在iOS中经过WebView加载Url或者请求HTTP时,如果连接中包含中文、特殊符号&%或是空格等都须要预先进行一下转码才可正常访问。ios

许久没编码,原先的方法已废弃了都,在此对应当前最新的方法进行记录:macos

 

官方源码“NSRUL.h”文件中能够看到以下信息:后两个方法已废弃,从iOS7.0开始提供新的两个方法:ide

@interface NSString (NSURLUtilities)

// Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.
- (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));

// Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.
@property (nullable, readonly, copy) NSString *stringByRemovingPercentEncoding API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));


- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc API_DEPRECATED("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.", macos(10.0,10.11), ios(2.0,9.0), watchos(2.0,2.0), tvos(9.0,9.0));
- (nullable NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc API_DEPRECATED("Use -stringByRemovingPercentEncoding instead, which always uses the recommended UTF-8 encoding.", macos(10.0,10.11), ios(2.0,9.0), watchos(2.0,2.0), tvos(9.0,9.0));

@end

 

一:stringByAddingPercentEncodingWithAllowedCharacters方法:是将普通字符转为百分比编码字符;编码

调用方法以下:spa

NSString *originalString = @"浙江省";
    
NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *encodeString = [originalString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];

eg. “浙江省”转码后即变成了“%E6%B5%99%E6%B1%9F%E7%9C%81”;code

 

方法二:stringByRemovingPercentEncoding方法:则是将百分比编码字符从新转会普通字符;component

调用方法以下:blog

NSString *decodeString = [encodeString stringByRemovingPercentEncoding];
相关文章
相关标签/搜索