Monday, May 13, 2013

NSString dataUsingEncoding example ios


Returns an NSData object containing a representation of the receiver encoded using a given encoding.
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
A string encoding.
Return Value of [NSString dataUsingEncoding]
The result of invoking dataUsingEncoding:allowLossyConversion: with NO as the second argument (that is, requiring lossless conversion).
Example of [NSString dataUsingEncoding]
NSString *msg = [NSString stringWithFormat:@"tell me \"where\"\n"
NSData *theData = [msg dataUsingEncoding:NSASCIIStringEncoding];
NSString* theString = [[NSString alloc] initWithData:theData encoding:NSASCIIStringEncoding];

BOOL isValid = [NSJSONSerialization isValidJSONObject:theString];
NSLog(@"Value %d %@",isValid, theString);
Example of [NSString dataUsingEncoding]
NSString to NSData:
NSString* str= @"teststring";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSData to NSString:
NSString* newStr = [[NSString alloc] initWithData:theData
Example of [NSString dataUsingEncoding]
NSString * jsonString = YOUR_STRING;
NSData * data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError * error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!json) {
    // handle error