2013-09-23 48 views
1

我試圖在應用程序啓動時從bundle resourcePath中獲取選定文件。我能夠獲取資源路徑中的所有文件,但是當我嘗試使用存儲在BGImage.plist中的名稱獲取文件時,出現錯誤「cocoa 260」(找不到指定路徑中的項目)。iOS - 將特定圖像從束資源路徑複製到文檔目錄

但是圖像出現在路徑上,我可以通過[文件管理器copyItemAtPath:bundlePath toPath:BGImagePath error:nil]獲取所有圖像;

下面的代碼不工作。(參考:iPhone (iOS): copying files from main bundle to documents folder error

NSString* BGImagePath =[[[AppDelegate applicationDocumentsDirectory] 
         URLByAppendingPathComponent:@"BGImages" isDirectory:YES] 
         path]; 
NSFileManager* fileManager = [NSFileManager defaultManager]; 
NSError *error = nil; 
NSArray *folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:BGImagePath error:&error]; 
NSString *bundlePath = [[NSBundle mainBundle] resourcePath]; 
NSString *BundleImagePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"BGImages.plist"];   //has file names 
bgImagesArray = [[NSArray arrayWithContentsOfFile:BundleImagePath] retain]; 

if (folderContents.count == 0) { 
    for (id obj in bgImagesArray) { 
      NSError* error; 
      if ([fileManager 
        copyItemAtPath:[bundlePath :obj] 
        toPath:[BGImagePath stringByAppendingPathComponent:obj] 
        error:&error]) 
       NSLog(@" *-> %@", [bundlePath stringByAppendingPathComponent:obj]); 
     } 
    } 
} 

是否有任何其他優雅的方式來獲得特定的文件,而無需在存儲的plist名字?

+0

如果你在一個「'NSError'」傳遞的對象,而不是「'nil'」變成「'copyItemAtPath'」的錯誤參數,你得到一個錯誤返回給你? bgImagesArray是否實際加載值? –

+0

邁克,問題已經修復。更新了答案。謝謝.. –

回答

1

這下面的代碼解決了該問題:

NSFileManager* fileManager = [NSFileManager defaultManager]; 
NSString* bgImagePath =[[[AppDelegate applicationDocumentsDirectory] 
         URLByAppendingPathComponent:@"BGImages" isDirectory:YES] 
         path]; 
[fileManager createDirectoryAtPath:bgImagePath withIntermediateDirectories:NO attributes:nil error:nil]; 
    NSArray * folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bgImagePath error:nil]; 
NSString * bundlePath = [[NSBundle mainBundle] resourcePath]; 
NSString * bundleImagePath = [[NSBundle mainBundle] pathForResource:@"BGImages" ofType:@"plist"]; 
NSArray* bgImagesArray = [NSArray arrayWithContentsOfFile:bundleImagePath]; 
if (folderContents.count == 0) { 
    [bgImagesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
     NSString * sourcePath = [bundlePath stringByAppendingPathComponent:obj]; 
     NSString * destinationPath = [bgImagePath stringByAppendingPathComponent:obj]; 
     [fileManager copyItemAtPath:sourcePath toPath:destinationPath error:nil]; 
    }]; 
} 
相關問題