ios 如何将 NSData 转换为 NSString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14456995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:57:17  来源:igfitidea点击:

How to Convert NSData to NSString

iphoneiosnsstringnsdata

提问by Nirav Bhatt

I know this has been asked quite before, and I already followed couple of approaches, but they don't work.

我知道以前有人问过这个问题,我已经采用了几种方法,但它们不起作用。

Following is what I already tried:

以下是我已经尝试过的:

NSString *newStr = [NSString stringWithUTF8String:[responseData bytes]];
NSString *newStr = [NSString stringWithFormat:@"%.*s", [responseData length], [responseData bytes]];

None of them works. In 1st case, it fills newStr with null. In 2nd, it fills with junk characters. I know from debugger log (po responseData) that I get valid response which is like bbbbbb 00 bbbbbb. [server sends them as byte array]

它们都不起作用。在第一种情况下,它用 null 填充 newStr。第二,它充满了垃圾字符。我从调试器日志(po responseData)知道我得到了有效的响应,就像 bbbbbb 00 bbbbbb。[服务器将它们作为字节数组发送]

What to do?

该怎么办?

EDIT: I am receiving this data from http request response - using ASIHTTPRequest library, in case anybody can help on that line.

编辑:我正在从 http 请求响应接收此数据 - 使用 ASIHTTPRequest 库,以防任何人都可以提供帮助。

采纳答案by Nirav Bhatt

I am posting this for records sake because I found a duplicateand voting to close this down.

我发布这个是为了记录起见,因为我发现了一个重复项并投票关闭它。

Actually what I am receiving is a stream of bytes represented as hex, and all the answers indicated do not work. Only [NSData description] gave me true data, which is something I can't use because it is intended for debugging.

实际上我收到的是一个以十六进制表示的字节流,并且所有指示的答案都不起作用。只有 [NSData description] 给了我真实的数据,这是我不能使用的,因为它用于调试。

Finally I tried the solution given here, and I get what I want. Thanks to all for trying to help out.

最后我尝试了这里给出的解决方案,我得到了我想要的。感谢所有尝试提供帮助的人。

回答by vinothp

Try this,

尝试这个,

NSData *responseData; [Initialize it]
NSString *receivedDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
NSLog(@"%@",receivedDataString);

回答by aknew

You can use this code lines

您可以使用此代码行

NSString *str=[[NSString alloc] initWithBytes:data1.bytes length:data1.length encoding:NSUTF8StringEncoding];

回答by Nimit Parekh

Please try following code

请尝试以下代码

NSString *string = [[[NSString alloc] initWithData: responseData.bytes encoding:NSUTF8StringEncoding] autorelease];

回答by Rahul Gupta

NSString  *image1Data = [[NSData dataWithData:myData] encodeBase64ForData];

But for this, you have to use NSData+Base64Additions class.

但是为此,您必须使用 NSData+Base64Additions 类。

回答by Nag Raj

Use following way

使用以下方式

 NSString *dC_Str = [[NSString alloc] initWithData:decryPtd_data encoding:NSASCIIStringEncoding] ;