gpt4 book ai didi

iPhone(iOS): copying files from main bundle to documents folder error

转载 作者:行者123 更新时间:2023-12-03 18:34:45 25 4
gpt4 key购买 nike

我正在尝试在首次启动时将应用程序包中的一些文件复制到文档目录中。我已经为首次启动进行了检查,但为了清楚起见,它们没有包含在代码片段中。问题是我正在复制到文档目录(已经存在)并且在文档中,它指出:

dstPath must not exist prior to the operation.

实现直接复制到文档根目录的最佳方法是什么?我想这样做的原因是为了允许 iTunes 文件共享支持。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Populator"];

NSLog(@"\nSource Path: %@\nDocuments Path: %@", sourcePath, documentsDirectory);

NSError *error = nil;

if([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:documentsDirectory error:&error]){
NSLog(@"Default file successfully copied over.");
} else {
NSLog(@"Error description-%@ \n", [error localizedDescription]);
NSLog(@"Error reason-%@", [error localizedFailureReason]);
}
...
return YES;
}

谢谢

最佳答案

您的目标路径必须包含要复制的项目的名称,而不仅仅是文档文件夹。尝试:

if([[NSFileManager defaultManager] copyItemAtPath:sourcePath 
toPath:[documentsDirectory stringByAppendingPathComponent:@"Populator"]
error:&error]){
...

编辑:抱歉误解了您的问题。不知道是否有更好的选择,然后迭代文件夹内容并单独复制每个项目。如果您的目标是 iOS4,您可以使用 NSArray 的 -enumerateObjectsUsingBlock: 函数来实现:

NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL];
[resContents enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSError* error;
if (![[NSFileManager defaultManager]
copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj]
toPath:[documentsDirectory stringByAppendingPathComponent:obj]
error:&error])
DLogFunction(@"%@", [error localizedDescription]);
}];

附注如果您不能使用 block ,您可以使用快速枚举:

NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL];

for (NSString* obj in resContents){
NSError* error;
if (![[NSFileManager defaultManager]
copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj]
toPath:[documentsDirectory stringByAppendingPathComponent:obj]
error:&error])
DLogFunction(@"%@", [error localizedDescription]);
}

关于iPhone(iOS): copying files from main bundle to documents folder error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3246109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com