我有一个表格单元格,我必须获取有关我正在下载的文件的更多信息,我设法得到了所有我需要但剩下的时间
这是我想要做的一个例子,除了时间计算之外,我已经完成了所有工作
获取文件大小:
fileSize = [NSNumber numberWithLongLong:[response expectedContentLength]]/(1024*1024);
下载:
[_responseData length]/(1024*1024)
速度:
double speed = [_responseData length] / ([NSDate timeIntervalSinceReferenceDate] - start);
其中start也是
中设置的[NSDate timeIntervalSinceReferenceDate]
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
剩余时间:???
问题:如何计算剩余时间?
答案 0 :(得分:2)
我想你需要做的是处理connection:didReceiveData:
委托方法。
@property (atomic, strong) NSDate *lastCheckDate;
@property (atomic, strong) NSDate *startDate;
@property (atomic, strong) NSNumber *fileSize;
@property (atomic, strong) NSNumber *sizeLeft;
- (void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data
{
NSDate *now = [NSDate date];
double dt = [now timeIntervalSinceDate:_lastCheckDate]; // time since last check
self.lastCheckDate = now;
double db = [data length]; // bytes received
double speed = db / dt;
self.sizeLeft = self.sizeLeft - [NSNumber numberWithDouble:db];
double averageSpeed = [(_fileSize - _sizeLeft) doubleValue] / [now timeIntervalSinceDate:_startDate];
// time left, based on current speed
double timeLeftCurrent = [sizeLeft doubleValue] / speed;
// time left, based on average speed
double timeLeftAverage = [sizeLeft doubleValue] / averageSpeed;
}
答案 1 :(得分:1)
在#kender的帮助下,我设法回答了我的问题
@interface TableViewController ()
{
NSTimeInterval start;
}
@property (atomic, strong) NSNumber *sizeLeft;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//in this method we get the file size and the start time
start = [NSDate timeIntervalSinceReferenceDate];
NSNumber *fileSize;
if ([response expectedContentLength] == NSURLResponseUnknownLength)
{
// unknown content size
fileSize = @0;
}
else
{
fileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}
self.sizeLeft = fileSize;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// _responseData is an NSData that i use to get the size i already downloaded
[_responseData appendData:data];
double speed = [_responseData length] / ([NSDate timeIntervalSinceReferenceDate] - start);
self.sizeLeft = [NSNumber numberWithDouble:[_sizeLeft doubleValue] - [data length]] ;
// time based on current speed
double timeLeft = [_sizeLeft doubleValue] / speed;
NSLog(@"time %.2f",timeLeft);
}