0

我需要在我的应用程序第一次运行时从主包中将一些 png 复制到文档文件夹。我需要它,因为我必须将这些图像的文件路径保存在核心数据实体中。

我试过这种方法,但它不起作用,有人知道为什么吗?

// 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];

谢谢

4

2 回答 2

5

createFileAtPath期望作为参数创建文件的路径,而不是封闭目录的路径。

评论:

  • 您还可以使用copyItemAtPath:toPath:error:复制文件而不将整个内容加载到内存中。
  • initWithFormat分配常量字符串的用法是不必要的。
  • stringByAppendingPathComponent:是附加路径组件的正确方法。
于 2013-07-09T07:33:26.683 回答
0

如何保存

-(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];
}

如何从沙盒加载

-(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;
}
于 2013-12-02T10:51:30.573 回答