2013-05-06 53 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師截短其餘的。