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

后端 未结 6 1831
日久生厌
日久生厌 2020-12-10 03:46

I am trying to set up my application so that on first launch, a series of files located in the \"Populator\" folder in the main bundle are copied into the documents director

6条回答
  •  误落风尘
    2020-12-10 04:03

    you should check whether the file already exists! Then copy.

    + (BOOL) getFileExistence: (NSString *) filename
    {
        BOOL IsFileExists = NO;
    
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        NSString *favsFilePath = [documentsDir stringByAppendingPathComponent:filename];
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
    
        // Check if the database has already been created in the users filesystem
        if ([fileManager fileExistsAtPath:favsFilePath])
        {
            IsFileExists = YES;
        }
        return IsFileExists;
    }
    
    + (NSString *)dataFilePath:(NSString *)filename {
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDirectory = [paths objectAtIndex:0];
        return [docDirectory stringByAppendingPathComponent:filename];
    }
    
    - (void)copyFileToLocal:(NSString *)filename
    {
    
        if (![AppDelegate getFileExistence:filename])
        {
            NSError *error;
            NSString *file = [[NSBundle mainBundle] pathForResource:filename ofType:nil];
    
            if (file)
            {
                if([[NSFileManager defaultManager] copyItemAtPath:file toPath:[AppDelegate dataFilePath:filename] error:&error]){
                    NSLog(@"File successfully copied");
                } else {
    
                    [[[UIAlertView alloc]initWithTitle:NSLocalizedString(@"error", nil) message: NSLocalizedString(@"failedcopydb", nil)  delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil)  otherButtonTitles:nil] show];
                    NSLog(@"Error description-%@ \n", [error localizedDescription]);
                    NSLog(@"Error reason-%@", [error localizedFailureReason]);
                }
                file = nil;
            }
        }
    }
    

    NSLocalizedString are localize strings of the application.

提交回复
热议问题