Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nsdictionary to nsdata

have an app that can take a picture and then upload to a server. encoding it to base 64 and pass it thru a XMLRPC to my php server.

i want to take the NSDictionary info that is returned from UIImagePickerController delegate

-(void) imagePickerController:(UIImagePickerController *)imagePicker didFinishPickingMediaWithInfo:(NSDictionary *)info

and convert it to NSData so i can encode it.

so, how can i convert NSDictionary to an NSData?

like image 385
Padin215 Avatar asked Aug 30 '11 20:08

Padin215


3 Answers

NSDictionary -> NSData:

    NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

NSData -> NSDictionary:

    NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
like image 90
Himanshu Mahajan Avatar answered Oct 08 '22 18:10

Himanshu Mahajan


You can use an NSKeyedArchiver to serialize your NSDictionary to an NSData object. Note that all the objects in the dictionary will have to be serializable (implement NSCoding at some point in their inheritance tree) in order for this to work.

Too lazy to go through my projects to lift code, so here is some from the Internet:

Encode

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
[archiver release];
/** data is ready now, and you can use it **/
[data release];

Decode:

NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
like image 24
Perception Avatar answered Oct 08 '22 17:10

Perception


I know a bit too late, but just in case someone bumps into this same issue. UIImage is not serializable, but you can serialize it using the code:

if your image is JPG:

NSData *imagenBinaria = [NSData dataWithData:UIImageJPEGRepresentation(imagen, 0.0)]; 

// imagen is a UIImage object

if your image is PNG:

NSData *imagenBinaria = [NSData dataWithData:UIImagePNGRepresentation(imagen)]; 

// imagen is a  UIImage object
like image 4
carlos_ms Avatar answered Oct 08 '22 16:10

carlos_ms