将应用程序中的图像复制到文档目录,然后重写它们

我有一个应用程序,我有一定数量的.jpg图片(大约300)。 因为它们实际上位于互联网中,所以它们可以作为开始的东西,但显然,在应用程序的第一次启动时,用户不要下载所有的应用程序,而是要预先打包。

每当我从服务器获得新的信息时,我都需要重写这些图像。 显然,我不能触摸应用程序包,所以我看到我的步骤是这样的:

  1. 在应用程序的第一次启动时,将包中的图像解包到文档目录中。
  2. 仅从文档目录访问它们,但不能从软件包访问它们。
  3. 如果有必要,我应该重写它们。

因此,我的代码将统一,因为我将始终使用相同的path来获取图像。

问题是,我对iOS中的整个文件系统知之甚less,所以我不知道如何将特定的包内容解压到Documents Directory,也不知道如何写入Documents Directory。

你能帮我一些代码,并确认我的解决scheme是正确的吗?

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *destPath = [documentsDirectory stringByAppendingPathComponent:@"images"]; //optionally create a subdirectory //"source" is a physical folder in your app bundle. Once that has a blue color folder (not the yellow group folder) // To create a physical folder in your app bundle: drag a folder from Mac's Finder to the Xcode project, when prompts // for "Choose options for adding these files" make certain that "Create folder references for …" is selected. // Store all your 300 or so images into this physical folder. NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"source"]; NSError *error; [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destPath error:&error]; if (error) NSLog(@"copying error: %@", error); 

根据OP的补充评论编辑:

要使用相同的文件名重写同一个目录,可以在写入之前使用fileExistsAtPath和removeItemAtPath的组合来检测和删除现有文件。

 if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; } // now proceed to write-rewrite 

试试这个代码

 -(void)demoImages { //-- Main bundle directory NSString *mainBundle = [[NSBundle mainBundle] resourcePath]; NSFileManager *fm = [NSFileManager defaultManager]; NSError *error = [[NSError alloc] init]; NSArray *mainBundleDirectory = [fm contentsOfDirectoryAtPath:mainBundle error:&error]; NSMutableArray *images = [[NSMutableArray alloc]init]; for (NSString *pngFiles in mainBundleDirectory) { if ([pngFiles hasSuffix:@".png"]) { [images addObject:pngFiles]; } } NSLog(@"\n\n Doc images %@",images); //-- Document directory NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDirectory = [paths objectAtIndex:0]; NSFileManager *fileManager = [NSFileManager defaultManager]; //-- Copy files form main bundle to document directory for (int i=0; i<[images count]; i++) { NSString *toPath = [NSString stringWithFormat:@"%@/%@",documentDirectory,[images objectAtIndex:i]]; [fileManager copyItemAtPath:[NSString stringWithFormat:@"%@/%@",mainBundle,[images objectAtIndex:i]] toPath:toPath error:NULL]; NSLog(@"\n Saved %@",fileManager); } }