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