- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.title = @"拷貝文件到Sandbox"; //文件類型 NSString * docPath = [[NSBundle mainBundle] pathForResource:@"save1" ofType:@"dat"]; // 沙盒Documents目錄 // NSString * appDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // 沙盒Library目錄 NSString * appDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]; //appLib Library/Caches目錄 NSString *appLib = [appDir stringByAppendingString:@"/Caches"]; BOOL filesPresent = [self copyMissingFile:docPath toPath:appLib]; if (filesPresent) { NSLog(@"OK"); } else { NSLog(@"NO"); } // 創建文件夾 NSString *createDir = [NSHomeDirectory() stringByAppendingString:@"/test"]; [self createFolder:createDir]; // 把文件拷貝到Test目錄 BOOL filesPresent1 = [self copyMissingFile:docPath toPath:createDir]; if (filesPresent1) { NSLog(@"OK"); } else { NSLog(@"NO"); } } /** * @brief 把Resource文件夾下的save1.dat拷貝到沙盒 * * @param sourcePath Resource文件路徑 * @param toPath 把文件拷貝到XXX文件夾 * * @return BOOL */ - (BOOL)copyMissingFile:(NSString *)sourcePath toPath:(NSString *)toPath { BOOL retVal = YES; // If the file already exists, we'll return success… NSString * finalLocation = [toPath stringByAppendingPathComponent:[sourcePath lastPathComponent]]; if (![[NSFileManager defaultManager] fileExistsAtPath:finalLocation]) { retVal = [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:finalLocation error:NULL]; } return retVal; } /** * @brief 創建文件夾 * * @param createDir 創建文件夾路徑 */ - (void)createFolder:(NSString *)createDir { BOOL isDir = NO; NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL existed = [fileManager fileExistsAtPath:createDir isDirectory:&isDir]; if ( !(isDir == YES && existed == YES) ) { [fileManager createDirectoryAtPath:createDir withIntermediateDirectories:YES attributes:nil error:nil]; } }
