無意中遇到一個問題,項目中使用UIWebView打不開web界面,檢查過URL和代碼,發(fā)現(xiàn)并沒有問題。隨考慮到一點:URL中包含漢字。
處理如下:
NSString *URLString = [NSString stringWithFormat:@"%@id=%@&email=%@",ProviderOrder,self.orderID,emailStr];
//方法是用來進行轉(zhuǎn)碼的,即將漢字轉(zhuǎn)碼
NSString *encodedString1 = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//該方法用來進行轉(zhuǎn)碼的,即將漢字轉(zhuǎn)碼(在Xcode7中,iOS9)
//NSString *encodedString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@",encodedString1]];
self.webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
self.webView.delegate = self;
NSURLRequest *request = [NSURLRequest requestWithURL:url ];
[self.webView loadRequest:request];
[self.view addSubview:self.webView];
上面為什么推薦使用
(NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters,
這里是文檔中給出的解釋:
其一:
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.
翻譯如下:
使用-stringByAddingPercentEncodingWithAllowedCharacters:改為,
它總是使用推薦的UTF-8編碼,
并且其對特定的URL組件或子組件進行編碼,因為每個URL組件或子組件對于什么字符是有效的具有不同的規(guī)則。
其二:
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.
翻譯如下:
通過替換不在allowedCharacters中的所有字符,使用百分比編碼字符返回從接收器創(chuàng)建的新字符串。 UTF-8編碼用于確定正確的百分比編碼字符。 整個URL字符串不能進行百分號編碼。 此方法旨在對URL組件或子組件字符串(而不是整個URL字符串)進行百分比編碼。 將忽略7位ASCII范圍之外的allowedCharacters中的任何字符。