WebView 打不开问题 (转码问题)

无意中遇到一个问题,项目中使用UIWebView打不开web界面,检查过URL和代码,发现并没有问题。随考虑到一点:URL中包含汉字

处理如下:

NSString *URLString = [NSString stringWithFormat:@"%@id=%@&email=%@",ProviderOrder,self.orderID,emailStr];
//方法是用来进行转码的,即将汉字转码
NSString *encodedString1 = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//该方法用来进行转码的,即将汉字转码(在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组件或子组件对于什么字符是有效的具有不同的规则。

其二:

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中的所有字符,使用百分比编码字符返回从接收器创建的新字符串。 UTF-8编码用于确定正确的百分比编码字符。 整个URL字符串不能进行百分号编码。 此方法旨在对URL组件或子组件字符串(而不是整个URL字符串)进行百分比编码。 将忽略7位ASCII范围之外的allowedCharacters中的任何字符。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,079评论 19 139
  • 编码问题一直困扰着开发人员,尤其在 Java 中更加明显,因为 Java 是跨平台语言,不同平台之间编码之间的切换...
    x360阅读 2,516评论 1 20
  • 1.将group中的产品信息展现到Cell中 先取出 group ,再取出group中的good 产品信息 2.把...
    whong736阅读 282评论 0 0
  • 这个世界长大了,越来越漂亮了。 我是它的创造者,却只能在它之外徘徊。我必须永生守护它,不能靠近。 这是我的宿命,既...
    鬼手大大阅读 177评论 0 0
  • 声明:配置环境是fedora 20,这里是官方文档,找文档是解决问题最有效的方式。 介绍 OpenShift是红帽...
    grunmin阅读 5,927评论 0 6