在 Objective C 中使用 NSStream 将 NSData 写入输出流所需的帮助

发布于 2024-09-28 13:26:05 字数 786 浏览 4 评论 0原文

我使用以下代码将文件从路径写入输出流,但每次运行代码时,它总是根据我的文件大小(8MB 或 5MB 等)向流写入 131768 字节。有人可以帮我检查一下吗?我似乎找不到问题。或者还有其他方法可以做到吗?我使用 NSStream 并使用以下代码:

NSString *filesContent = [[NSString alloc] initWithContentsOfFile:myMediaFile];           // myMediaFile is a path to my file eg. .../Documents/myvideo.mp4/

NSData *data = [ filesContent dataUsingEncoding:NSASCIIStringEncoding        allowLossyConversion:YES];

const uint8_t *buf = [data bytes];

NSUInteger length = [data length];
 NSLog(@"datalen = %d",length);
 NSInteger nwritten = [outputStream write:buf maxLength:length];

 if (-1 == nwritten) {
  NSLog(@"Error writing to stream %@: %@", outputStream, [outputStream streamError]);
 }else{
  NSLog(@"Wrote %ld bytes to stream %@.", (long long)nwritten, outputStream);
 }

i using the following code which writes the file from a path to an output stream but every time i run the code, it always write 131768 bytes to the stream regards of my file size(8MB or 5MB or etc). Can someone please check for me? i can't seems to find the problem. Or it there other ways to do it? I'm using NSStream with the following code:

NSString *filesContent = [[NSString alloc] initWithContentsOfFile:myMediaFile];           // myMediaFile is a path to my file eg. .../Documents/myvideo.mp4/

NSData *data = [ filesContent dataUsingEncoding:NSASCIIStringEncoding        allowLossyConversion:YES];

const uint8_t *buf = [data bytes];

NSUInteger length = [data length];
 NSLog(@"datalen = %d",length);
 NSInteger nwritten = [outputStream write:buf maxLength:length];

 if (-1 == nwritten) {
  NSLog(@"Error writing to stream %@: %@", outputStream, [outputStream streamError]);
 }else{
  NSLog(@"Wrote %ld bytes to stream %@.", (long long)nwritten, outputStream);
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

锦爱 2024-10-05 13:26:05

这是How to use NSOutputStream's write message?的重复,不是我很惊讶你没有找到那个。

底线; write:maxLength: 方法不一定会一次性写入您传递给它的所有数据。由于涉及缓冲,因此您可能需要循环写入数据,因为输出流上有可用空间。

请注意,我所说的“循环”并不是指“民意调查”。

This is a duplicate of How to use NSOutputStream's write message?, not that I'm surprised you didn't find that one.

Bottom line; the write:maxLength: method isn't necessarily going to write all the data you pass to it all at once. There is buffering involved and, thus, you'll likely need to loop writing data as space is available on the output stream.

Note that by "loop", I do not mean "poll".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文