如何确定使用NSURLConnection下载的文件的大小(以字节为单位)? [英] How to determine the size (in bytes) of a file downloading using NSURLConnection?
问题描述
我需要知道我使用NSURLConnection(GET)下载到我的应用程序中文件的大小(以字节为单位).这是我下面的字节接收代码(如果有帮助的话).我需要知道的是如何获取文件大小(以字节为单位),以便可以使用它来显示UIProgressView.
I need to know the size of the file I am downloading (in bytes) into my app using NSURLConnection (GET). Here is my bytes recieved code below if it helps. What I need to know is how to get the filesize in bytes so that I can use it to show a UIProgressView.
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
// A delegate method called by the NSURLConnection as data arrives. We just
// write the data to the file.
{
#pragma unused(theConnection)
NSInteger dataLength;
const uint8_t * dataBytes;
NSInteger bytesWritten;
NSInteger bytesWrittenSoFar;
assert(theConnection == self.connection);
dataLength = [data length];
dataBytes = [data bytes];
bytesWrittenSoFar = 0;
do {
bytesWritten = [self.fileStream write:&dataBytes[bytesWrittenSoFar] maxLength:dataLength - bytesWrittenSoFar];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self _stopReceiveWithStatus:@"File write error"];
break;
} else {
bytesWrittenSoFar += bytesWritten;
} while (bytesWrittenSoFar != dataLength);
}
推荐答案
[数据长度]确实以字节为单位返回数据大小,这应该为您提供所需的数字.
[data length] does return the size of the data in bytes which should give you the figure you're looking for.
但是NSData提供了-writeToFile:atomically:和-writeToFile:options:error方法用于将数据写入磁盘,因此我不知道您为什么要编写自己的文件I/O.
But NSData provides -writeToFile:atomically: and -writeToFile:options:error methods for writing data to disk so I don't know why you're writing your own file I/O.
这篇关于如何确定使用NSURLConnection下载的文件的大小(以字节为单位)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!