iOS:在应用程序启动时从捆绑包复制文件
当用户第一次使用我的应用程序时,它应该将一个配置文件从捆绑包复制到某个文件夹中。然后,用户可以摆弄这个文件,如果他们把它弄乱了,他们只需按“还原”即可删除该文件并从捆绑包中再次复制它iOS:在应用程序启动时从捆绑包复制文件,ios,copy,bundle,nsfilemanager,Ios,Copy,Bundle,Nsfilemanager,当用户第一次使用我的应用程序时,它应该将一个配置文件从捆绑包复制到某个文件夹中。然后,用户可以摆弄这个文件,如果他们把它弄乱了,他们只需按“还原”即可删除该文件并从捆绑包中再次复制它 - (void) resetPresets { LOG_( @"Copying tunings file from original..." ); // copy default tunings -> curr tunings file NSString* appSupportDi
- (void) resetPresets
{
LOG_( @"Copying tunings file from original..." );
// copy default tunings -> curr tunings file
NSString* appSupportDir = [NSFileManager appSupportDir];
NSString* tuningsPath = [appSupportDir stringByAppendingPathComponent: @"tunings.txt"];
NSBundle* bundle = [NSBundle mainBundle];
NSString* origTuningsPath = [bundle pathForResource: @"tuningsOriginal"
ofType: @"txt" ];
NSFileManager* fileManager = [NSFileManager defaultManager];
NSError* error = nil;
if( [fileManager fileExistsAtPath: tuningsPath] )
{
[fileManager removeItemAtPath: tuningsPath
error: & error ];
if( error )
LOG( @"\n ERROR: %@ \n %@ \n", [error userInfo], [error localizedFailureReason] );
}
assert( [fileManager fileExistsAtPath: origTuningsPath] );
[fileManager copyItemAtPath: origTuningsPath
toPath: tuningsPath
error: & error ];
if( error )
LOG( @"\n ERROR: %@ \n %@ \n", [error userInfo], [error localizedFailureReason] );
LOG( @"done!" );
// load profiles from it
[self loadProfilesFromFile: tuningsPath ];
// auto-sets active preset index to 0 & saves prefs
self.activeThemeIndex = 0;
}
依赖于一个简单的类别:
#import "NSFileManager+addons.h"
@implementation NSFileManager ( NSFileManager_addons )
+ (NSString *) appSupportDir
{
NSArray* paths = NSSearchPathForDirectoriesInDomains(
NSApplicationSupportDirectory,
NSUserDomainMask,
YES
);
NSString* appSupportDir = [paths objectAtIndex: 0];
return appSupportDir;
}
@end
这是导致问题的线路:
[fileManager copyItemAtPath: origTuningsPath
toPath: tuningsPath
error: & error ];
这是控制台输出:
[预设初始化]预设->首次运行!默认设置
预设正在从原始文件复制调谐文件。。。错误:{
目的地路径=
“/var/mobile/Applications/38FC3C65-74AF-4892-B48D-A3508A8CF404/Library/Application
Support/tunings.txt”;
NSFilePath=
“/var/mobile/Applications/38FC3C65-74AF-4892-B48D-A3508A8CF404/Fork.app/tuningsOriginal.txt”;
NSUserStringVariant=Copy;}没有这样的文件或目录
为什么它抱怨没有这样的文件或目录?显然,不应该存在这样的文件。当你把一个文件复制到一个新的位置时,你并不希望有一个文件在那里
所以我猜它是在抱怨目录。但我已经用一种相当标准的方法找到了目录。发生了什么事?这不是要使用的正确目录吗?还是我做错了什么?由
NSSearchPathForDirectoriesInDomains返回的目录不保证存在;如果需要,您需要自己创建它们(请参阅)。NSFileManager可以提供帮助