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

感謝

回答

5

createFileAtPath預計爲參數要創建文件的路徑,而不是道路封閉目錄的 。

備註:

  • 您還可以使用copyItemAtPath:toPath:error:沒有裝載 整個內容的文件複製到內存中。
  • 使用initWithFormat來分配一個常量字符串是不必要的。
  • stringByAppendingPathComponent:是追加路徑組件的正確方法。
+0

我試圖加載此:[[的NSFileManager defaultManager] copyItemAtPath:mainBundleFilePath toPath:documentsDirectory誤差:無];但不起作用。 – Totka

+0

@Totka:正如我所說:參數是*文件路徑*,而不是目錄。 –

+0

如何獲取文件路徑?不是[destPath objectAtIndex:0]? – Totka

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; 
} 
相關問題