arraysobjective-cnsdata

Byte Array to NSData


In a WebService JSON response is coming. In the response, there is image is coming as a byte array. I have to show the image in a UIImageView. I am trying to convert the byte array to NSData. But not getting how to do that. Any help would be appreciated. I am confident that the byte array has image data in it. Sample Byte array for your reference:

unsigned char array = {
            137,
            80,
            78,
            71,
            ...
            66,
            96,
            130
};

Thanks


Solution

  • You have to convert the JSON to an array of strings first; you can, for example, use the NSJSONSerialization class:

    NSArray *strings = [NSJSONSerialization JSONObjectWithData:theJSONString options:kNilOptions error:NULL];
    

    Then walk the strings array, convert each entry to an integer, and add it to an allocated byte pointer/array:

    unsigned c = strings.count;
    uint8_t *bytes = malloc(sizeof(*bytes) * c);
    
    unsigned i;
    for (i = 0; i < c; i++)
    {
        NSString *str = [strings objectAtIndex:i];
        int byte = [str intValue];
        bytes[i] = byte;
    }
    

    Then finally make an NSData out of the bytes, then init an UIImage object using it:

    NSData *imageData = [NSData dataWithBytesNoCopy:bytes length:c freeWhenDone:YES];
    UIImage *image = [UIImage imageWithData:imageData];