Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Copy Files without freezing GUI

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

How would you go about that? Any ideas?


P.S.

Upvotes: 2

Views: 443

Answers (1)

Shams Ahmed
Shams Ahmed

Reputation: 4513

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.

Upvotes: 6

Related Questions