11

tenga una aplicación que pueda tomar una foto y luego subirla a un servidor. codificándolo en base 64 y pasándolo a través de un XMLRPC a mi servidor php.Convierta nsdictionary a nsdata

Quiero aprovechar la información NSDictionary que se devuelve desde UIImagePickerController delegado

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

y convertirlo en NSData para que pueda codificar.

Entonces, ¿cómo puedo convertir NSDictionary en NSData?

Respuesta

23

Puede usar un NSKeyedArchiver para serializar su NSDictionary a un objeto NSData. Tenga en cuenta que todos los objetos en el diccionario tendrán que ser serializables (implementar NSCoding en algún punto en su árbol de herencia) para que esto funcione.

Demasiado perezoso para ir a través de mis proyectos para levantar código, por lo que aquí es un poco de Internet:

Codificar

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]; 
+0

he intentado implementando esto, pero sigo recibiendo un error cuando para codificarlo: 2011-08-30 15: 46: 18.468 Satshot [1986: 307] - [UIImage encodeWithCoder:]: selector no reconocido enviado a la instancia 0x630de50 2011-08-30 15: 46: 18.502 Satshot [1986 : 307] *** Aplicación de finalización debido a excepción no detectada 'NSInvalidArgumentException', razón: '- [UIImage encodeWithCoder:]: selector no reconocido enviado a instancia 0x630de50' información es lo que obtengo del delegado UIImagePickerController que debería ser un nsdictionary . También probé [archiver encodeObject: info] y obtuve el mismo error. – Padin215

+0

el error ocurre en [archiver encodeRootObject: info]; y es un error "SIGABRT", sry por olvidarse de mencionar eso. – Padin215

+2

UIImage no se puede serializar con NSKeyedArchiver, no sin soluciones temporales. – Perception

4

Conozco un poco demasiado tarde , pero solo en caso de que alguien se encuentre con este mismo problema. UIImage no es serializable, pero se puede serializar utilizando el código:

si su imagen es JPG:

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

// imagen is a UIImage object 

si su imagen es PNG:

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

// imagen is a UIImage object 
4

La clase NSPropertyListSerialization que la dan la mayoría del control sobre la escritura y la lectura de listas de propiedades:

NSDictionary *dictionary = @{@"Hello" : @"World"}; 
NSData *data = [NSPropertyListSerialization dataWithPropertyList:dictionary 
              format:NSPropertyListBinaryFormat_v1_0 
              options:0 
              error:NULL]; 

Leer:

NSData *data = ... 
NSPropertyListFormat *format; 
NSDictionary *dictionary = [NSPropertyListSerialization propertyListWithData:data 
                 options:0 
                 format:&format 
                 error:NULL]; 
+0

Obtiene la advertencia –

+1

la lectura no es correcta ... Error NSError *; formato NSPropertyListFormat; NSDictionary * dictionary = [NSPropertyListSerialization propertyListWithData: self.inputFormEncodedDictionary opciones: 0 formato: & error de formato: & error]; –

4

NSDictionary -> NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary]; 

NSData -> NSDictionary:

NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData]; 
opciones se me ocurren en este
3

Tres, dos mencionado en otras respuestas NSKeyedArchiver y PropertyList, también hay NSJSONSeriali zación que me dio los datos más compactos en una prueba simple.

NSDictionary *dictionary = @{@"message":@"Message from a cool guy", @"flag":@1}; 
NSData *prettyJson = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil]; 
NSData *compactJson = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil]; 
NSData *plist = [NSPropertyListSerialization dataWithPropertyList:dictionary 
                  format:NSPropertyListBinaryFormat_v1_0 
                  options:0 
                  error:NULL]; 
NSData *archived = [NSKeyedArchiver archivedDataWithRootObject:dictionary];` 

Tamaño resultados para los diferentes enfoques de menor a mayor

  • compactJson 46 bytes
  • prettyJson 57 bytes
  • plist 91 bytes
  • archivadas 316 bytes