将图像从应用程序复制到文档目录并在之后重写它们

将图像从应用程序复制到文档目录并在之后重写它们

本文介绍了将图像从应用程序复制到文档目录并在之后重写它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,其中包含一定数量的 .jpg 图片(大约 300 张).它们可以作为开始使用,因为它们实际上位于 Internet 中,但显然用户在应用程序第一次启动时不要下载所有这些,而是​​将它们预先打包更方便.

I have an app where I have a certain amount of .jpg pictures (roughly 300). They serve as something to start with, because they're actually located in the internet, but obviously it's more convenient for user not to download all of them at the first start of the App, but to have them pre-packed.

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

I am required to rewrite these images everytime I get new information from server. Obviously, I can't touch the app bundle, so I see my steps like this:

  1. 在应用程序第一次启动时将图像从包解压到文档目录.
  2. 只能从 Documents Directory 访问它们,而不能从 bundle 中访问它们.
  3. 如果有必要,我应该重写它们.

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

And thus my code will be unified, cause I will always use the same path to get the image.

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

The problem is that I know very little about the whole file system thing in iOS, so I don't know how to unpack the particular bundle contents to Documents Directory and also I don't know how to write to Documents Directory either.

你能帮我写一些代码并确认我的解决方案是正确的吗?

Could you please help me with some code and also confirm that my solution scheme is right?

推荐答案

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 的其他评论进行

Edited per additional comment from the OP:

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

To rewrite with the same file name to the same directory, you can use a combination of fileExistsAtPath and removeItemAtPath to detect and remove the existing file before writing.

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

这篇关于将图像从应用程序复制到文档目录并在之后重写它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 11:40