iPhone (iOS): copying files from main bundle to documents folder error

后端 未结 2 872
面向向阳花
面向向阳花 2020-12-09 00:03

I am trying to copy some files across from my app bundle to the documents directory on first launch. I have the checks in place for first launch, but they\'re not included i

相关标签:
2条回答
  • 2020-12-09 00:38

    Your destination path must contain the name of item being copied, not just the documents folder. Try:

    if([[NSFileManager defaultManager] copyItemAtPath:sourcePath 
              toPath:[documentsDirectory stringByAppendingPathComponent:@"Populator"]
              error:&error]){
    ...
    

    Edit: Sorry misunderstood your question. Don't know if there's a better option then iterating through folder contents and copy each item separately. If you're targeting iOS4 you can use NSArray's -enumerateObjectsUsingBlock: function for that:

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

    P.S. If you can't use blocks you can use fast enumeration:

    NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL];
    
    for (NSString* obj in resContents){
        NSError* error;
        if (![[NSFileManager defaultManager] 
                     copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] 
                     toPath:[documentsDirectory stringByAppendingPathComponent:obj]
                     error:&error])
                DLogFunction(@"%@", [error localizedDescription]);
        }
    
    0 讨论(0)
  • 2020-12-09 00:38

    a note:
    don't issue lengthy operation in didFinishLaunchingWithOptions: is a conceptual mistake. If this copy takes too much time, watchdog will kill you. launch it in a secondary thread or NSOperation... I personally use a timer proc.

    0 讨论(0)
提交回复
热议问题