2010-07-26 34 views
3

我想從我的MainBundle/SampleImages文件夾複製到應用程序NSDocumentDirectory /庫文件夾的幾個圖像文件,但我無法這樣做。我已經檢查過這些圖像是在.app/Mainbundle/SampleImages目錄下的,我也檢查過在NSDocumentsDirectory中創建了Library文件夾,但是沒有文件被複制。iPhone:無法從MainBundle複製到NSDocumentDirectory

我嘗試了兩種方法,下面給出,但沒有成功。 這裏是我用來複制文件的代碼。

第一種方法

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0];  
     NSString *documentLibraryFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Library"]; 

     NSString *resourceSampleImagesFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SampleImages"]; 
     NSData *mainBundleFile = [NSData dataWithContentsOfFile:resourceSampleImagesFolderPath]; 
     [[NSFileManager defaultManager] createFileAtPath:documentLibraryFolderPath 
               contents:mainBundleFile 
               attributes:nil]; 

第二種方法

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0];  
     NSString *documentSampleImagesFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Library"]; 

     NSString *resourceSampleImagesFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SampleImages/"]; 
     [fileManager createDirectoryAtPath: documentSampleImagesFolderPath attributes:nil]; 
     if([fileManager copyItemAtPath:resourceSampleImagesFolderPath toPath:documentSampleImagesFolderPath error:&error]) { 
      NSLog(@"success"); 
     } 
     else { 
      NSLog(@"Failure"); 
      NSLog(@"%d",error); 
     } 

我已經花了幾個尋找一個解決方案時,這裏的任何幫助,將不勝感激。

謝謝

Shumais哈克

回答

2

我得到了它與第二個方法實現通過改變它咬了。 由於SDK文檔說目標目錄不能存在,因此不需要創建該目錄。

NSFileManager *fileManager = [NSFileManager defaultManager]; 
     NSError *error; 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                  NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Library"]; 

     NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] 
               stringByAppendingPathComponent:@"SampleImages"]; 
      [fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error]; 
+0

無用:錯誤域= NSCocoaErrorDomain代碼= 260 ...文件不存在 – 2016-07-22 15:00:58