[PHImageManager] imageData has appended garbage bytes

Originator:warorface
Number:rdar://18370050 Date Originated:
Status:Closed Resolved:
Product:iOS SDK Product Version:8.0 (12A365)
Classification:Duplicate Reproducible:Always
 
Summary:
The imageData NSData returned by PHImageManager has appended garbage bytes full of zeros. 
The length of these bytes varies between assets (and perhaps, runs)

Steps to Reproduce:
- Open attached project.
- Compile & Run on device.

Expected Results:
Data returned by PHImageManager should be the same as the obtained from ALAssetRepresentation

Actual Results:
Data returned by PHImageManager contains garbage bytes, easily noted because are only zeros

Version:
8.0 (12A365)

Notes:


Configuration:
iPhone 5c (Model A1456, A1532)

Attachments:
'PhotosZeroBytesBugDemo.zip' was successfully uploaded.
Demo project: http://cl.ly/0o2n3g0Y3p40

–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

Current Workaround/Fix

#define BUFFER_LENGTH 16

NS_INLINE NSData *VDTrimmedZeroBytesData(NSData *data) {
    NSRange dataRange = NSMakeRange(0, data.length);
    unsigned char *buffer = malloc(BUFFER_LENGTH);
    BOOL stop = NO;
    
    while (!stop) {
        NSRange bufferRange = NSMakeRange(dataRange.length-BUFFER_LENGTH, BUFFER_LENGTH);
        [data getBytes:buffer range:bufferRange];
        for (int i = (BUFFER_LENGTH-1); i > 0; i--) {
            unsigned char byte = buffer[i];
            if (byte != 0) {
                stop = YES;
                break;
            }
            dataRange.length = dataRange.length-1;
        }
    }
    free(buffer);
    
    if (dataRange.length == data.length) {
        return data;
    } else {
        return [data subdataWithRange:dataRange];
    }
}

@implementation PHImageManager (compatibleImageData)

- (PHImageRequestID)vd_requestImageDataForAsset:(PHAsset *)asset options:(PHImageRequestOptions *)options resultHandler:(void (^)(NSData *, NSString *, UIImageOrientation, NSDictionary *))resultHandler
{
    return [self requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
        resultHandler(VDTrimmedZeroBytesData(imageData), dataUTI, orientation, info);
    }];
}

@end

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!