iOS 字符串含有特殊字符,转换URL为空值

 
网略请求的url含有特殊字符时字符串需要编码处理
比如:url:http://demo.demo.com/demo?{userToken:xxxxxx}等等,都需要字符串处理,否则转换成NSURL可能为空值。
 

第一种方法

url含有中文的解决方法

 NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlStr,NULL,NULL,kCFStringEncodingUTF8));

urlStr是url地址,拼接中含有中文。

 

第二种方法

// 在对URL中的中文进行转码时,iOS 9之前我们使用
 [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//编码
// iOS 9之后使用 
 [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//编码
 
URLQueryAllowedCharacterSet组件是可选的
编码字符范围
URLFragmentAllowedCharacterSet  "#%<>[]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[]^`{|}
URLQueryAllowedCharacterSet     "#%<>[]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[]^`

解码:[@"编码后的字符串" stringByRemovingPercentEncoding];//解码


NSURL 转换字符串可以直接使用NSURL的属性absoluteString
例如上述的url,NSString * urlStr = url.absoluteString;

 

使用上面的方法无效,解决方法使用这个

//urlEncode编码

NSString *charactersToEscape = @"?!@#$^&%*+,:;='"`<>()[]{}/\| ";

NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];

NSString * stringUrl = [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];

//urlEncode解码

NSMutableString *outputStr = [NSMutableString stringWithString:input];

[outputStr replaceOccurrencesOfString:@"+" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[outputStr length])];

[outputStr stringByRemovingPercentEncoding];

    

 

 

参考:https://www.jianshu.com/p/b7dde2b1e992

   http://blog.csdn.net/olive1993/article/details/52036755

   https://www.tpyyes.com/a/kuozhan/2017/0406/89.html

 

原文地址:https://www.cnblogs.com/lulushen/p/8527361.html