Question

I need to copy some png to documents folder from the main bundle at the first run of my app. I need it because I have to save the file path of these images in a core data entity.

I tried in that way, but it don't works, anybody knows why?

// to copy image from main bundle to documents folder

NSString* mainBundleFilePath = [[NSBundle mainBundle] pathForResource:@"SbriciolataDiRicotta" ofType:@"png"];

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

 NSData *mainBundleFile = [NSData dataWithContentsOfFile:mainBundleFilePath];
[[NSFileManager defaultManager] createFileAtPath:documentsDirectory
                                        contents:mainBundleFile
                                      attributes:nil];

// to save the file path

NSString*nomeImmagine = [[NSString alloc] initWithFormat:@"SbriciolataDiRicotta"];
NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@.png",documentsDirectory, nomeImmagine];

Thanks

Was it helpful?

Solution

createFileAtPath expects as argument the path of file to be created, not the path of the enclosing directory.

Remarks:

  • You can also use copyItemAtPath:toPath:error: to copy the file without loading the entire contents into memory.
  • The usage of initWithFormat to assign a constant string is unnecessary.
  • stringByAppendingPathComponent: is the correct method to append a path component.

OTHER TIPS

How to save

-(void)saveImageWithID:(NSString*)ID{
    //[self saveImageWithID:<#(NSString *)#>];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString* imageName = [[NSString alloc] initWithFormat:@"%@",ID];
    NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@.png",documentsDirectory, imageName];

    UIImage *image = self.fieldImage.image;
    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
    [data1 writeToFile:pngFilePath atomically:NO];
}

How to load from sandbox

-(void) loadImageFromPathInsideView
{
    // [self loadImageFromPathInsideView];
    Contatto* contact =[[DataManager sharedClass]dammiIlTuttoIlContattoDellaCella:self.indice];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString* imageName = [[NSString alloc] initWithFormat:@"%@", contact.nome2];
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [NSString stringWithFormat:@"%@/%@.png",documentsDirectory, imageName];;
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    self.fieldImage.image = image;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top