使用NSFileManager在复制文件期间更新进度条

时间:2022-02-19 05:54:58

I copy files then my application is finish launching from resource to caches directory. but I want to update my progress bar during copying the files.

我复制文件然后我的应用程序完成从资源启动到缓存目录。但我想在复制文件时更新我的​​进度条。

I copy the file with the code below:

我使用以下代码复制文件:

-(BOOL)copyDirectory:(NSString*)source toDirectory:(NSString*)targat
{
    BOOL retVal = YES;
    NSFileManager *fileManager = [[NSFileManager alloc] init];

    NSError *error;
    if ([fileManager fileExistsAtPath:targat] == YES)
    {
        NSError *error = nil;
        [fileManager removeItemAtPath:targat error:&error];
    }


    if(![fileManager copyItemAtPath:source
                             toPath:targat
                              error:&error])
    {
        NSLog(@"Error copy files: %@", [error description]);
        retVal = NO;
    }
    [fileManager release];

    return retVal;
}

I can not think about a good idea, how to update the progress bar According to the progress of copying files.

我想不出一个好主意,如何更新进度条根据复制文件的进度。

1 个解决方案

#1


6  

In high level you may approach the following :

在高级别,您可以接近以下内容:

  1. Run your copying process in a seperate thread (P1)
  2. 在单独的线程中运行复制过程(P1)

  3. Run another thread (P2) which reads periodically (say every 100ms) the destination file current_size.
  4. 运行另一个线程(P2),它定期读取(比如每100ms)目标文件current_size。

  5. Calculate current_size / total_size
  6. 计算current_size / total_size

  7. Update you progress bar UI element
  8. 更新进度条UI元素

Then you just want to find out the size of a file, you don't actually have to open it. Just use NSFileManager like this:

然后你只想找出一个文件的大小,你实际上不需要打开它。只需像这样使用NSFileManager:

NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.finalPath error:NULL];
unsigned long long fileSize = [attributes fileSize]; // in bytes

#1


6  

In high level you may approach the following :

在高级别,您可以接近以下内容:

  1. Run your copying process in a seperate thread (P1)
  2. 在单独的线程中运行复制过程(P1)

  3. Run another thread (P2) which reads periodically (say every 100ms) the destination file current_size.
  4. 运行另一个线程(P2),它定期读取(比如每100ms)目标文件current_size。

  5. Calculate current_size / total_size
  6. 计算current_size / total_size

  7. Update you progress bar UI element
  8. 更新进度条UI元素

Then you just want to find out the size of a file, you don't actually have to open it. Just use NSFileManager like this:

然后你只想找出一个文件的大小,你实际上不需要打开它。只需像这样使用NSFileManager:

NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.finalPath error:NULL];
unsigned long long fileSize = [attributes fileSize]; // in bytes