Agregar información de encabezado a NSData

I want to send image through iOS devices by BSD Socket.

As we know, an image is divided into several packages to be sent out, So the receiver needs the size of the image.

So I want to insert the size to the beginning of the images's binary data.

NSData* image = UIImagePNGRepresentation(screenShot);
NSUInteger len = [image length];
NSMutableData *header = [[NSMutableData alloc] initWithBytes:&len length:sizeof(NSUInteger)];
[header appendData:msg];

Receiver get the NSData and parse

NSUInteger len;
[header getBytes:&len length:sizeof(NSUInteger)]

I tried to insert int, char and NSString, but I never get the right number of the size. What's wrong with my solution? Are there better ones?

preguntado el 24 de agosto de 12 a las 08:08

Your code is fine. Must be something else. -

2 Respuestas

Destinador

uint32_t len = [image length];
NSLog(@"Len = %u", len);
NSMutableData *header = [NSMutableData dataWithCapacity:sizeof(len) + len];
[header appendBytes:htonl(len) length:sizeof(len)];  // use network order
[header appendData:image];

Receptor

uint32_t len;
[header getBytes:&len length:sizeof(uint32_t)];
len = ntohl(len); // network to host
printf("Len = %u\n", len);

Respondido 24 ago 12, 13:08

I finally solved the problem with iOS NSData+Base64 Category http://projectswithlove.com/projects/NSData_Base64.zip

Respondido 31 ago 12, 07:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.