在我的应用中,用户可以下载大文件(1GB +)。我有自己的进度视图来指示下载进度。我正在使用AFNetworking
这样的
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead){
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
double progress = (double)(size + totalBytesRead) / (size + totalBytesExpectedToRead);
[[NSNotificationCenter defaultCenter] postNotificationName:ETBDownloadManagerProgressNotification object:component userInfo:@{ ETBDownloadProgressKey : [NSNumber numberWithDouble:progress], ETBDownloadExpectedSizeKey : [NSNumber numberWithDouble:(size + totalBytesExpectedToRead)*1.0/1024.0/1024.0] }];
}];
我在下载文件时遇到性能问题。同时,只能下载一个文件。 Time Profiler显示我更新UI并经常调用drawRect:
。所以这是我的进度视图setProgress:
- (void)setProgress:(double)progress
{
_progress = progress;
if (_progress > 1)
_progress = 1;
self.textLabel.text = [NSString stringWithFormat:@"%.f%%", 100*self.progress];
[self setNeedsDisplay];
}
进度视图drawRect:
- (void)drawRect:(CGRect)rect
{
UIBezierPath* bezierPath = [UIBezierPath bezierPath];
[bezierPath addArcWithCenter:CGPointMake(rect.size.width/2, rect.size.height/2)
radius:rect.size.width/2 - kLineWidth/2 - kPadding
startAngle:0
endAngle:2*M_PI
clockwise:YES];
bezierPath.lineWidth = kLineWidth;
[[UIColor colorWithRed:1 green:1 blue:1 alpha:.3] setStroke];
[bezierPath stroke];
bezierPath = [UIBezierPath bezierPath];
[bezierPath addArcWithCenter:CGPointMake(rect.size.width/2, rect.size.height/2)
radius:(rect.size.width/2 - kLineWidth - kPadding)/2
startAngle:startAngle
endAngle:(endAngle - startAngle) * self.progress + startAngle
clockwise:YES];
bezierPath.lineWidth = rect.size.width/2 - kLineWidth - kPadding;
[[UIColor colorWithRed:1 green:1 blue:1 alpha:.3] setStroke];
[bezierPath stroke];
}
问题是如何避免滞后?我发现的唯一方法是减少用于更新UI的postNotification
个数。但是怎么样?我尝试在if (i++%3 == 0)
内使用setDownloadProgressBlock
之类的条件,但它很难看:)
我还尝试将self.textLabel.text = ...
替换为drawRect:
,但这没有任何意义。
也许可以设置下载包的大小?
答案 0 :(得分:2)
i ++%3 == 0可能很丑,但不是很糟糕,我会做的更像是
// outside of the loop
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
__block double progressTmp = 0;
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead){
double progress = (double)(size + totalBytesRead) / (size + totalBytesExpectedToRead);
// if there was a significant change in progress ratio
if ((progress - progressTmp) > 0.05) {
[[NSNotificationCenter defaultCenter] postNotificationName:ETBDownloadManagerProgressNotification object:component userInfo:@{ ETBDownloadProgressKey : [NSNumber numberWithDouble:progress], ETBDownloadExpectedSizeKey : [NSNumber numberWithDouble:(size + totalBytesExpectedToRead)*1.0/1024.0/1024.0] }];
progressTmp = progress;
}
}];
0.05可能必须更改为更符合您需求的内容。