我需要在第一次运行应用程序时从主包中复制一些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];
由于
答案 0 :(得分:5)
createFileAtPath
期望创建 file 的路径作为参数,而不是路径
封闭的目录。
说明:
copyItemAtPath:toPath:error:
复制文件而不加载
把整个内容都记录下来。initWithFormat
来分配常量字符串。stringByAppendingPathComponent:
是附加路径组件的正确方法。答案 1 :(得分: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;
}