从mianbundle拷贝文件到sandbox中
这儿有段代码,教大家如何拷贝文件。
- - (void) copySampleFilesToMyDocumentsFolder {
- NSError *error;
- NSFileManager *fileManager = [NSFileManager defaultManager];
- NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
- NSArray *dirContents = [fileManager contentsOfDirectoryAtPath: bundleRoot error: &error];
- NSArray *onlyPdf = [dirContents filteredArrayUsingPredicate: [NSPredicate predicateWithFormat: @"self ENDSWITH '.jpg'"]];
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentsDir = [paths objectAtIndex: 0];
- for (int i = 0; i < onlyPdf.count; i++) {
- NSString *pdfName = [onlyPdf objectAtIndex: i];
- NSString *docPdfFilePath = [documentsDir stringByAppendingPathComponent: pdfName];
- //Using NSFileManager we can perform many file system operations.
- BOOL success = [fileManager fileExistsAtPath: docPdfFilePath];
- if (!success) {
- NSString *samplePdfFile = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: pdfName];
- success = [fileManager copyItemAtPath: samplePdfFile toPath: docPdfFilePath error: &error];
- if (!success){}
- // NSAssert1(0, @"Failed to copy file '%@'.", [error localizedDescription]);
- //debugLog(@"Failed to copy %@ file, error %@", pdfName, [error localizedDescription]);
- else {
- //debugLog(@"File copied %@ OK", pdfName);
- }
- }
- else {
- //debugLog(@"File exits %@, skip copy", pdfName);
- }
- }
- }
如果希望列出在应用包的图片目录中所有以jpg为文件后缀名的JPEG图片,需要用到pathsForResourcesOfType:inDirectory:方法:
NSArray *birds = [[NSBundle mainBundle] pathsForResourcesOfType:@"jpg" inDirectory:@"birdImages"];
这个方法返回路径名的数组。如果JPEG并未储存在应用的子目录中,可以指定@""作为inDirectory:参数。