开发者

Unicode data from NSData to NSString

开发者 https://www.devze.com 2023-02-09 10:29 出处:网络
So if I have NSData from an HTTP request, then I do something like this: NSString *test = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

So if I have NSData from an HTTP request, then I do something like this:

NSString *test = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

This will result in null if the data contains weird unicode data (title is from reddit):

{"title":"click..██me..and..then██________ ██check██_开发者_开发技巧.your...██.__...██____ ██....██████████████....██____ ██████....██████....██████____ ██████████████████████____ ....██████████████████______ ........██..._recently....██________ ....██....viewed....links....██_____"},

How would I convert the data to a string? Ideally, it would best if the string wasn't null so I could parse it as JSON, but even a lossy conversion is fine with me in these cases.

I'm not familiar with unicode (naive American I am), so any enlightenment about that would be a nice bonus :)


If I copy and paste that text into a UTF-8 text file, read it with dataWithContentsOfURL: and convert it to a string with initWithData:encoding:, it works fine. The most likely explanation is that you are not getting valid UTF-8 data.

0

精彩评论

暂无评论...
验证码 换一张
取 消