2013-05-06 54 views
0

我想在我的应用程序中实现一个进度条。发生的过程是应用程序将目录复制到iOS文档目录中。通常需要7-10秒(iPhone 4测试)。我对进度条的理解是当事情正在发生时更新吧。但是基于目录代码的复制,我不知道如何知道它有多远。UIProgressView酒吧在过程中

任何人都可以提供任何建议或例子如何做到这一点?进度条码在下面并且复制目录代码。

谢谢!

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]; 
    } 
} 
+0

看到这个线程:http://stackoverflow.com/questions/10414802/how-显示进度的复制一个大文件在ios – Amit 2013-05-06 06:12:17

+0

@ amit3117谢谢阿米特!我是新来的Objective-C,我如何根据链接的建议启动单独的线程?谢谢 – Teddy13 2013-05-06 06:14:21

+1

通过调用启动一个计时器:[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(targetMethod :) userInfo:nil repeatats:YES];这会在0.5秒内回复targetMethod。那么您可以更新在targetMethod中复制的进度条计算百分比,如下面的答案所示。 – Amit 2013-05-06 06:24:00

回答

1

定义的NSTimer *定时器在.h文件中

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]; 
    } 
} 
+0

谢谢!我得到浮动*进度的错误。错误是“使用不兼容的float类型初始化float”。有什么建议么? – Teddy13 2013-05-06 06:31:55

+1

更新了答案。现在检查 :) – Ushan87 2013-05-06 06:33:09

1

如果需要这么长的时间,因为该目录中有很多文件,您可以逐个复制循环中的文件。要确定进度,您可以/应该简单地假定复制每个文件需要相同的时间。

请注意,您不希望在7-10秒内阻止UI,因此您需要在单独的非主线程上复制。设置进度条,像所有的UI代码,需要使用平均线程上完成的:

dispatch_async(dispatch_get_main_queue(),^
{ 
    progressBar.progress = numberCopied/(float)totalCount; 
}); 

演员到float你咯(取决于文件的数量)更好的准确性给出,因为一个纯粹的int师截短其余的。