简体   繁体   English

将 NSData 分成三个块 - 以我开始的更多字节结束

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

I have an iOS app that has video upload functionality.我有一个具有视频上传功能的 iOS 应用程序。 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.我需要将视频数据上传到具有非常具体的上传要求的服务器:最大文件大小为 15 MB,并且文件上传必须通过不超过 5 MB 的块上传。

I am using subdataWithRange to split the video file into three NSData chunks.我使用subdataWithRange将视频文件拆分为三个NSData块。 This way the file chunks will never exceed 5 MB, regardless of the total file size.这样,无论文件总大小如何,文件块都不会超过 5 MB。 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.我将 NSData 对象分成三个块并检查了大小,结果发现我以更多的字节结束。 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.我相信我已经正确设置了范围,以便将对象分成三个块。

The ranges are (start, length) not (start, end).范围是(开始,长度)而不是(开始,结束)。 You do: (0, 710998), (710998, 1421996), (1421996, 710999).你这样做:(0, 710998), (710998, 1421996), (1421996, 710999)。 It should be: (0, 710998), (710998, 710998) and (1421996, 710999)应该是:(0, 710998), (710998, 710998) 和 (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))];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM