WebView 打不開問題 (轉(zhuǎn)碼問題)

無意中遇到一個問題,項目中使用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中的任何字符。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,648評論 19 139
  • 編碼問題一直困擾著開發(fā)人員,尤其在 Java 中更加明顯,因為 Java 是跨平臺語言,不同平臺之間編碼之間的切換...
    x360閱讀 2,581評論 1 20
  • 1.將group中的產(chǎn)品信息展現(xiàn)到Cell中 先取出 group ,再取出group中的good 產(chǎn)品信息 2.把...
    whong736閱讀 310評論 0 0
  • 這個世界長大了,越來越漂亮了。 我是它的創(chuàng)造者,卻只能在它之外徘徊。我必須永生守護它,不能靠近。 這是我的宿命,既...
    鬼手大大閱讀 223評論 0 0
  • 聲明:配置環(huán)境是fedora 20,這里是官方文檔,找文檔是解決問題最有效的方式。 介紹 OpenShift是紅帽...
    grunmin閱讀 6,005評論 0 6

友情鏈接更多精彩內(nèi)容