NSString initWithData 返回 nil
我与服务器一起工作。我向服务器发送请求,它以 UTF-8
编码回答我,但是当我尝试将字节数组解码为字符串时,有时我会得到 nil
值。如何解码这个字节数组而不出现任何错误?
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString * result_string=[[[NSString alloc] initWithData:receivedData encoding:NSNonLossyASCIIStringEncoding] autorelease];
NSLog(result_string);
//...
}
当我使用 NSUTF8StringEncoding
进行转换时,我得到如下内容:
xt":"","newstype":[{"id":"1","name":"\u043f\u0440\u043e\u0438\u0441\u0448\u0435\u0441\u0442\u0432\u0438 \u0435","ic
当我使用转换时NSNonLossyASCIIStringEncoding
我得到这样的信息:
xt":"","newstype":[{"id":"1","name":"происшествие","ic
但有时,使用 NSNonLossyASCIIStringEncoding
进行转换时,我会收到错误。我不知道为什么
I work with server. I send request to the server and it answers me in UTF-8
encoding, but when I try to decode byte array to the string, sometimes I get nil
value. How can I decode this bytes array without any errors?
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString * result_string=[[[NSString alloc] initWithData:receivedData encoding:NSNonLossyASCIIStringEncoding] autorelease];
NSLog(result_string);
//...
}
when I convert using NSUTF8StringEncoding
I get something like this:
xt":"","newstype":[{"id":"1","name":"\u043f\u0440\u043e\u0438\u0441\u0448\u0435\u0441\u0442\u0432\u0438\u0435","ic
when I convert using NSNonLossyASCIIStringEncoding
I get something like this:
xt":"","newstype":[{"id":"1","name":"происшествие","ic
but sometimes, converting using NSNonLossyASCIIStringEncoding
, I get errors. I don't know why
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您说您的服务器发送以 UTF-8 编码的数据,但在您的代码中您使用 ASCII 对其进行解码。
将编码设置为 NSUTF8StringEncoding。
You say that your server sends data encoded in UTF-8, but in your code you're decoding it with ASCII.
Set encoding to NSUTF8StringEncoding.
我认为您可能需要将终止“0”附加到您的数据中。
来自我的项目之一:
然后使用正确的编码照常执行。
I think you might need to append the terminating "0" to your data.
From one of my projects:
Then perform as usual with the correct encoding.
我不知道为什么会发生这个错误。我是这样修复的:
I don't know why this error happened. I fixed it like this:
我在使用 RestKit 时遇到了同样的问题。方法 [response bodyToString] 不适用于西里尔字母编码。我通过切换到 NSWindowsCP1251StringEncoding 解决了这个问题。
I faced the same problem while using RestKit. Method [response bodyToString] was not working with cyrillic encoding. I solved it by switched to NSWindowsCP1251StringEncoding.