在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];