在iOS中通过WebView加载Url或者请求HTTP时,若是链接中包含中文、特殊符号&%或是空格等都需要预先进行一下转码才可正常访问。
官方源码“NSRUL.h”文件中可以看到如下信息:后两个方法已废弃,从iOS7.0开始提供新的两个方法:
@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方法:是将普通字符转为百分比编码字符;
调用方法如下:
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”;
方法二:stringByRemovingPercentEncoding方法:则是将百分比编码字符重新转会普通字符;
调用方法如下:
NSString *decodeString = [encodeString stringByRemovingPercentEncoding];
网友评论