我想在我的应用程序中实现一个进度条。发生的过程是应用程序将一个目录复制到iOS文档目录中。通常需要7-10秒(测试过的iPhone 4)。我对进度条的理解是,你可以随着事情的发生而更新进度条。但基于目录代码的复制,我不确定如何知道它进行了多长时间。
有人能就如何做到这一点提供任何建议或例子吗?下面是进度条码和目录代码的复印件。
谢谢!
UIProgressView *progressView = [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleBar];
progressView.progress = 0.75f;
[self.view addSubview: progressView];
[progressView release];
//Takes 7-10 Seconds. Show progress bar for this code
if (![fileManager fileExistsAtPath:dataPath]) {
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *imageDataPath = [bundlePath stringByAppendingPathComponent:_dataPath];
if (imageDataPath) {
[fileManager copyItemAtPath:imageDataPath toPath_:dataPath error:nil];
}
}
发布于 2013-05-06 14:17:43
在.h文件中定义NSTimer *timer
if (![fileManager fileExistsAtPath:dataPath]) {
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *imageDataPath = [bundlePath stringByAppendingPathComponent:_dataPath];
timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(updateProgressView) userInfo:nil repeats:YES];
[timer fire];
if (imageDataPath) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[fileManager copyItemAtPath:imageDataPath toPath_:dataPath error:nil];
};
}
}
并添加此方法
- (void) updateProgressView{
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *imageDataPath = [bundlePath stringByAppendingPathComponent:_dataPath];
NSData *allData = [NSData dataWithContentsOfFile:imageDataPath];
NSData *writtenData = [NSData dataWithContentsOfFile:dataPath];
float progress = [writtenData length]/(float)[allData length];
[pro setProgress:progress];
if (progress == 1.0){
[timer invalidate];
}
}
发布于 2013-05-06 14:13:32
如果因为该目录中有许多文件而花费这么长时间,您可以在循环中逐个复制这些文件。要确定进度,您可以/应该简单地假设复制每个文件需要相同的时间。
请注意,您不希望在这7-10秒内阻塞UI,因此您需要在单独的非主线程上进行复制。与所有UI代码一样,需要在平均线程上使用以下命令来设置进度条:
dispatch_async(dispatch_get_main_queue(), ^
{
progressBar.progress = numberCopied / (float)totalCount;
});
转换为float
会稍微提高精度(取决于文件的数量),因为纯int
除法会截断余数。
https://stackoverflow.com/questions/16392865
复制相似问题