Copy Files without freezing GUI

心不动则不痛 提交于 2020-01-15 04:13:30

问题


OK, so basically here's what I want to do :

  • I have a list of files in my app bundle, e.g. in folder myData (please note: there are lots of files/folders within subfolders/etc)
  • I want to copy the whole file tree to a given location on user's disk
  • I need to have access to each separate file being copied, since some of them will need to be processed before being copied.

How would you go about that? Any ideas?


P.S.

  • I know about NSFileWrapper's writeFile:atomically:updateFilenames, but it doesn't gie me access to each file
  • I already have a method for getting the file tree for a specific folder. However, it still seems to me kinda slow. Is there any built-in (or more Cocoa-friendly) way for that?
  • Since there are quite a lot of files, the whole process must run so that the GUI does not freeze

回答1:


use Grand Central Dispatch(GCD) to run method in asynchronously thread using

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // user disk space - will use user document
    NSString *docuemntPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    // app bundle folder
    NSString *bundleRoot = [[NSBundle mainBundle] resourcePath];
    NSString *folderPath = [bundleRoot stringByAppendingPathComponent:@"aFolder"];

    NSArray *files = [[NSFileManager defaultManager] enumeratorAtPath:folderPath].allObjects;

    for (NSString *aFile in [files objectEnumerator]) { 
        NSString *copyPath = [folderPath stringByAppendingPathComponent:aFile];
        NSString *destPath = [docuemntPath stringByAppendingPathComponent:aFile];

        NSError *error;
        if ([[NSFileManager defaultManager] copyItemAtPath:copyPath toPath:destPath error:&error]) {
            NSLog(@"Copying successful");
            // here add a percent to progress view 
        } else {
            NSLog(@"Copying error: %@", error.userInfo);
        } 
    }

  // When the copying is finished update your UI 
  // on the main thread and do what ever you need with the object 
  dispatch_async(dispatch_get_main_queue(), ^{
    [self someMethod:myData];
  });
});

and on your main thread use a UIProgressView to indicate the progress of file operation from the number of files/folder.



来源:https://stackoverflow.com/questions/18333143/copy-files-without-freezing-gui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!