IOS Convert URL string to NSString?

2019-07-04 03:19发布

I have a problem to convert an URL string, which I extract from XML file to NSString.

The URL string look like this, it looks like odd but it is URL format.

%3CTEXTFORMAT%20LEADING%3D%222%22%3E%3CP%20ALIGN%3D%22LEFT%22%3E%3CFONT%20FACE%3D%22Arial%22%20SIZE%3D%2212%22%20COLOR%3D%22%23000000%22%20LETTERSPACING%3D%220%22%20KERNING%3D%220%22%3E%u53F0%u5317%u7E2323141%u65B0%u5E97%u6C11%u6B0A%u8DEF130%u5DF714%u865F5%u6A13%3C/FONT%3E%3C/P%3E%3C/TEXTFORMAT%3E

However, when I use stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding method, it return nil.

After some experiment and research, seems this URL contain %u cause problem while converting URL and this %u looks like unicode, however, I try to remove all %u then stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding method return a proper string without any problem.

Does anyone know how can I convert this URLstring to NSString properly?

1条回答
劫难
2楼-- · 2019-07-04 04:18

It is Unicode han characters in your urlString thats why it is not converting.

Replace %u to \u and you will get your String.

NSString *str=@"%3CTEXTFORMAT%20LEADING%3D%222%22%3E%3CP%20ALIGN%3D%22LEFT%22%3E%3CFONT%20FACE %3D%22Arial%22%20SIZE%3D%2212%22%20COLOR%3D%22%23000000%22%20LETTERSPACING%3D%220%22%20KERNING%3D%220%22%3E%u53F0%u5317%u7E2323141%u65B0%u5E97%u6C11%u6B0A%u8DEF130%u5DF714%u865F5%u6A13%3C/FONT%3E%3C/P%3E%3C/TEXTFORMAT%3E";
str=[str stringByReplacingOccurrencesOfString:@"%u" withString:@"\\u"];
NSString *convertedStr=[str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"converted string is %@ \n",convertedStr);

output :---------------

converted string is <TEXTFORMAT LEADING="2"><P ALIGN="LEFT"><FONT FACE="Arial" SIZE="12" COLOR="#000000" LETTERSPACING="0" KERNING="0">\u53F0\u5317\u7E2323141\u65B0\u5E97\u6C11\u6B0A\u8DEF130\u5DF714\u865F5\u6A13</FONT></P></TEXTFORMAT>

for more Info follow this url
This is chinese unicode char here is some code that will prove it:

NSString *newStr=@"\u53F0\u5317\u7E2323141\u65B0\u5E97\u6C11\u6B0A\u8DEF130\u5DF714\u865F5\u6A13";
NSLog(@"chinese string is %@",[newStr stringByReplacingPercentEscapesUsingEncoding:NSUTF16StringEncoding]);

output:---------------------- 台北縣23141新店民權路130巷14號5樓

go to google translate converting this string will give you someone's address. as :-

Citizens Xindian, Taipei County 23141 Road 130, 5th Floor, No. 14, Lane

查看更多
登录 后发表回答