在iOS程序访问HTTP资源时需要对URL进行Encode
1.转换为UTF8(ios7 之后的方法)
NSString*charactersToEscape =@"我的生活";
NSCharacterSet*allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString*netStr1 = [charactersToEscape stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
转换之后的结果为
%E6%88%91%E7%9A%84%E7%94%9F%E6%B4%BB
2.转换为Unicode
-(NSString*) utf8ToUnicode:(NSString*)string
{
NSUIntegerlength = [stringlength];
NSMutableString*s = [NSMutableStringstringWithCapacity:0];
for(inti =0;i < length; i++)
{
unichar_char = [stringcharacterAtIndex:i];
//判断是否为英文和数字
if(_char <='9'&& _char >='0')
{
[sappendFormat:@"%@",[stringsubstringWithRange:NSMakeRange(i,1)]];
}
elseif(_char >='a'&& _char <='z')
{
[sappendFormat:@"%@",[stringsubstringWithRange:NSMakeRange(i,1)]];
}
elseif(_char >='A'&& _char <='Z')
{
[sappendFormat:@"%@",[stringsubstringWithRange:NSMakeRange(i,1)]];
}
else
{
[sappendFormat:@"\\u%x",[stringcharacterAtIndex:i]];
}
}
returns;
}
转换“我的生活”的结果为
\u6211\u7684\u751F\u6D3B
网友评论