在iOS App安装上创建子文件夹

时间:2014-07-08 14:28:22

标签: ios xcode swift

我想在我的应用程序的文档文件夹中创建一个图像文件夹,以容纳我稍后下载的一堆图像。首次安装应用程序时如何创建此文件夹?我确信它是Xcode中的一个我无法找到的设置......

1 个答案:

答案 0 :(得分:1)

这是我在第一次运行应用程序时创建目录的方式,放在AppDelegate中:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
  (NSDictionary*)launchOptions {

/////////////////////////////////////////
// Create Content directories if needed
/////////////////////////////////////////

NSFileManager *filemgr;
NSArray *dirPaths;
NSString *docsDir;
NSString *newDir;
NSString *thumbNails;
NSString *largeImages;

filemgr =[NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                               NSUserDomainMask, YES);
docsDir = dirPaths[0];

// Picture Directory
newDir = [docsDir stringByAppendingPathComponent:@"/myPictures"];
if(![filemgr fileExistsAtPath:newDir])
{
    NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/myPictures"]];
    NSError *error;
    [[NSFileManager defaultManager] createDirectoryAtPath:[docsDir stringByAppendingPathComponent:@"/myPictures"] withIntermediateDirectories:YES attributes:nil error:&error];
    [data writeToFile:newDir atomically:YES];
}

// Nested Thumbnail Directory
thumbNails =[docsDir stringByAppendingPathComponent:@"/myPictures/thumb"];
if(![filemgr fileExistsAtPath:thumbNails])
{
    NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/myPictures/thumb"]];
    NSError *error;
    [[NSFileManager defaultManager] createDirectoryAtPath:[docsDir stringByAppendingPathComponent:@"/myPictures/thumb"] withIntermediateDirectories:YES attributes:nil error:&error];
    [data writeToFile:thumbNails atomically:YES];
}