iOS中文参数的URL地址URLEncode转码

来源:互联网 发布:淘宝推广能做运营么 编辑:程序博客网 时间:2024/06/08 10:46

   *生成URL对象时,如果链接中含有中文参数时,用这个带有中文参数的链接创建的NSURL对象会为空。


   *以这个链接为例://http://app.enails.cn/serives/name.ashx?userid=20170321074746&username=张三


         NSString *urlString = @"http://app.enails.cn/serives/name.ashx?userid=20170321074746&username=张三";

     NSURL *url = [NSURL URLWithString:urlString];

    

   *此时url为nil,因为URL的参数中含有中文字符,此刻又没对urlString进行URLEncode转码,造成创建的NSURL对象为空。


     *所以我们要对这个urlString进行URLEncode转码,方法如下:


     NSString *urlString = @"http://app.enails.cn/serives/name.ashx?userid=20170321074746&username=张三";    

     //对urlString进行URLEncode转码

     //URLQueryAllowedCharacterSet 返回一个包含字符的字符集允许一个URL的查询组件。

     NSCharacterSet *encode_set= [NSCharacterSet URLQueryAllowedCharacterSet];

     NSString *urlString_encode = [urlString stringByAddingPercentEncodingWithAllowedCharacters:encode_set];

     NSURL *url = [NSURL URLWithString:urlString_encode];


    *附:https://developer.apple.com/documentation/foundation/nscharacterset?changes=latest_major&language=objc (NSCharacterSet的官方文档)



阅读全文
0 0