简体   繁体   中英

Converting NSData to NSString

I am parsing a URL, I am getting some data in a NSMutableData object ie urlData . Now in - (void)connectionDidFinishLoading:(NSURLConnection *)connection {} I would like to convert the urlData to a NSString . I have tried with:

NSString *responseData =  [NSString stringWithCString:[urlData bytes] length:[urlData length]];   
NSString* responseData = [NSString stringWithUTF8String:[urlData bytes]];   
NSString *responseData = [[NSString alloc] initWithBytes:[urlData bytes] length:[urlData length] encoding:NSUTF8StringEncoding] ;   
NSString *responseData = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];   
NSString *responseData = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]; 

I am either getting null in NSString object or PK(reverse Question Marks which i am unable to show you).

Can anyone give me a solution for this?

-(id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding

is the method you need to use. Your problem is either that you are not using the correct encoding or the data is not string data. NSLog the data and examine it to figure pout what it really is.

From the Apple documents:

An NSString object initialized by converting the bytes in data into Unicode characters using encoding. The returned object may be different from the original receiver. Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding).

Use below code it will work

NSString *str=[[NSString alloc] initWithBytes:[urlData bytes] length:[urlData length] encoding:NSStringEncodingConversionAllowLossy]; 
NSLog(@"urlData........%@",str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM