我有一个应用程序,我有一定数量的.jpg图片(大约300)。它们可以作为开始使用的东西,因为它们实际上位于互联网中,但显然用户不会在应用程序的第一次启动时下载所有这些内容,而是让它们预先打包。
每次从服务器获取新信息时,我都需要重写这些图像。显然,我无法触摸应用程序包,所以我看到了这样的步骤:
因此我的代码将统一,因为我将始终使用相同的路径来获取图像。
问题是我对iOS中的整个文件系统事物知之甚少,所以我不知道如何将特定的包内容解压缩到Documents Directory,而且我也不知道如何写入Documents Directory
您能否帮我一些代码,并确认我的解决方案是正确的?
答案 0 :(得分:2)
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
答案 1 :(得分:0)
试试此代码
-(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);
}
}