8
votes

I am trying to copy a folder from the application bundle to iphone document directory but it isnt happening.

I have used this codes

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Photos"];


    NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths1 objectAtIndex:0];

    NSError *error1;
    NSArray *resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error: &error1];
    if (error1) {
        NSLog(@"error1 : %@",error1);
    }
    [resContents enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         NSError* error;
         if (![[NSFileManager defaultManager]
               copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj]
               toPath:[documentsDirectory stringByAppendingPathComponent:obj]
               error:&error])
             NSLog(@"%@", [error localizedDescription]);
     }];
}

And also tried this approach

- (void)viewDidLoad{
     [self copyFolder];
    }

- (void) copyFolder {
    BOOL success1;
    NSFileManager *fileManager1 = [NSFileManager defaultManager];
    fileManager1.delegate = self;
    NSError *error1;
    NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
    NSString *writableDBPath1 = [documentsDirectory1 stringByAppendingPathComponent:@"/Photos"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:writableDBPath1])
        [[NSFileManager defaultManager] createDirectoryAtPath:writableDBPath1 withIntermediateDirectories:NO attributes:nil error:&error1];

    NSString *defaultDBPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Photos"];
    NSLog(@"default path %@",defaultDBPath1);
    success1 = [fileManager1 copyItemAtPath:defaultDBPath1 toPath:writableDBPath1 error:&error1];
    if (!success1 )
    {
        NSLog(@"error1 : %@",error1);
    } else {
    }
}

- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath{
    if ([error code] == 516) //error code for: The operation couldn’t be completed. File exists
        return YES;
    else
        return NO;
}

Its display this error

Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x8a39800 {NSUnderlyingError=0x8a385b0 "The operation couldn’t be completed. No such file or directory", NSFilePath=/Users/user/Library/Application Support/iPhone Simulator/7.0.3/Applications/FC7F93EE-CFB7-41CF-975B-2E3B18760202/app.app/Photos, NSUserStringVariant=( Folder )}

But Here is the folder

enter image description here

4
The yellow color Photos represents a group name. A physical folder has a blue color. - user523234
Attention the "Photos" in your project not a real folder but the group (Images.xcassets for example is real folder) - andproff
@user523234 thanx for reply got it. - Dilip
@proff thanx for reply got it - Dilip

4 Answers

4
votes

Photos seems like a group and not a folder reference. Hence all the images photo1.jpg.. etc are stored directly under your resource bundle.

The path <resource_bundle>/Photos does not exists. To verify this go to the application .app

.app->Right-click->Show Package Contents

Instead of adding Photos as a group, add it as Folder reference and under your target Copy Bundle Resources make sure the entire folder is added.

Hope that helps!

1
votes

Your photos is not in the Photos directory. They just exist in /Users/devubhamanek/Library/Application Support/iPhone Simulator/7.0.3/Applications/FC7F93EE-CFB7-41CF-975B-2E3B18760202/MTPhotoViewer.app/ like /Users/devubhamanek/Library/Application Support/iPhone Simulator/7.0.3/Applications/FC7F93EE-CFB7-41CF-975B-2E3B18760202/MTPhotoViewer.app/photo1.jpg

If you want to create an directory in bundle, you should add the files in Photos directory like this: enter image description here.

The folder in your project navigator should be:enter image description here

1
votes

Make sure you folder exists. You can easily assign your group in XCode to physical folder

Click on group and you'll find location setting on right pane.

Press on folder sign to choose physical folder location.

Actually this is really helpful to keep your project structure clean (not only in XCode project) but physically on disk.

enter image description here

1
votes

Swift 3 Complete Solution Code Note: After creating folder with reference use following method.

func copyFolderFromThisAppMainToUserDocument(folderName: String) -> Bool {

    let fileMgr = FileManager.default
    let userDocumentURL = fileMgr.urls(for: .documentDirectory, in: .userDomainMask).first!
    let urlForCopy = userDocumentURL.appendingPathComponent(folderName, isDirectory: true)
    if let bundleURL = Bundle.main.url(forResource: folderName, withExtension: "") {
        // if exist we will copy it
        do {
            try fileMgr.copyItem(at: bundleURL, to: urlForCopy)
            return true
        } catch let error as NSError { // Handle the error
            print("\(folderName) copy failed! Error:\(error.localizedDescription)")
            return false
        }
    } else {
        print("\(folderName) not exist in bundle folder")
        return false
    }
}