美文网首页
WebView 打不开问题 (转码问题)

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

作者: WheatDen | 来源:发表于2017-08-22 23:48 被阅读80次

    无意中遇到一个问题,项目中使用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中的任何字符。

    相关文章

      网友评论

          本文标题:WebView 打不开问题 (转码问题)

          本文链接:https://www.haomeiwen.com/subject/dymrdxtx.html