user559142 user559142 - 4 months ago 26
Objective-C Question

Printing NSData using NSLog

How can I print the contents of an NSData object using NSLog:

-(void) post:(NSString*) msg to:(NSString*) link{
NSString *myRequestString = [NSString stringWithFormat:@"message=%@", msg];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: link]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: myRequestData];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
NSLog("%@", *returnData); //doesn't work

}


I would like to print the contents of *returnData...

Answer

If you do this:

NSLog(@"%@", returnData); 

The NSData will be logged in hex format. I think that is probably what you are after.

If you want to turn it into a string and log the string, you first need to find out what character set was used. The default character set for HTTP is not UTF-8, it is ISO-8859-1. One way to do that is to examine the Content-Type header for the charset section.

Comments