objective-cbytensdatansrangensuinteger

Split NSData into three chunks - Ending up with MORE bytes that I started with


I have an iOS app that has video upload functionality. I need to upload video data to a server that has very specific upload requirements: max file size 15 MB and the file upload must be uploaded via chunks that do NOT exceed 5 MB.

I am using subdataWithRange to split the video file into three NSData chunks. This way the file chunks will never exceed 5 MB, regardless of the total file size. I split the NSData object into three chunks and checked the size, it turns out that I am ending up with MORE bytes that I started with. I'm a special kind of stupid I know.

Here is my code:

// Get the video data object.
NSData *postData = [self getAttachmentData];
    
// Get the file size in bytes.
NSUInteger fileSizeBytes = [postData length];
    
// Split the video into three chunks.
NSData *chunkOne = [postData subdataWithRange:NSMakeRange(0, (fileSizeBytes / 3))];
NSData *chunkTwo = [postData subdataWithRange:NSMakeRange([chunkOne length], ((fileSizeBytes / 3) * 2))];
NSData *chunkThree = [postData subdataWithRange:NSMakeRange([chunkTwo length], (fileSizeBytes - [chunkTwo length]))];
         
NSLog(@"fileSizeBytes: %lu", (unsigned long)fileSizeBytes);
NSLog(@"\n\n");
NSLog(@"chunckOne: %lu", (unsigned long)[chunkOne length]);
NSLog(@"chunckTwo: %lu", (unsigned long)[chunkTwo length]);
NSLog(@"chunckThree: %lu", (unsigned long)[chunkThree length]);
NSLog(@"\n\n");
NSLog(@"chunkTotal: %lu", ((unsigned long)[chunkOne length] + (unsigned long)[chunkTwo length] + (unsigned long)[chunkThree length]));

Here is the output log:

fileSizeBytes: 2132995
 
chunckOne: 710998
chunckTwo: 1421996
chunckThree: 710999

chunkTotal: 2843993

So what am I doing wrong? I believe I have set the ranges correctly, so that the object is divided into three chunks.


Solution

  • The ranges are (start, length) not (start, end). You do: (0, 710998), (710998, 1421996), (1421996, 710999). It should be: (0, 710998), (710998, 710998) and (1421996, 710999)

    NSUInteger chunkSizeBytes = (fileSizeBytes / 3)
    NSData *chunkOne = [postData subdataWithRange:NSMakeRange(0, chunkSizeBytes)];
    NSData *chunkTwo = [postData subdataWithRange:NSMakeRange(chunkSizeBytes, chunkSizeBytes)];
    NSData *chunkThree = [postData subdataWithRange:NSMakeRange(chunkSizeBytes * 2, fileSizeBytes - (chunkSizeBytes * 2))];