将文件从NSBundle复制到Documents错误

时间:2012-08-05 19:39:38

标签: objective-c ios ios5

我想将文件从应用程序NSBundle复制到Documents目录。

我怎么能让这段代码无法运行:

-(NSString*)copyFile:(NSString*)name{


    NSString *storePath = [[[appDelegate applicationDocumentsDirectory] absoluteString] stringByAppendingPathComponent:name];

    NSError *error;

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:storePath]) {
        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"recordTest" ofType:@"caf"];
        if (defaultStorePath) {
            if ([fileManager fileExistsAtPath:defaultStorePath]) {
                [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:&error];
                 NSLog(@"Error: %@)" , [error localizedDescription]);
            }


        }
    }
    return storePath;
}

此打印操作无法完成。

更详细:

Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0xd629530 {NSUserStringVariant=(
    Copy
), NSFilePath=/var/mobile/Applications/D0183043-3FD2-4341-8DA4-E1D140E556F6/test.app/recordTest.caf, NSDestinationFilePath=file:/localhost/var/mobile/Applications/D0183043-3FD2-4641-8DA4-E5D140E556F6/Documents/recordTest.caf, NSUnderlyingError=0xd629970 "The operation couldn’t be completed. No such file or directory"}

如果我在复制之前检查,我不明白为什么没有这样的文件。

有什么想法吗?

由于

2 个答案:

答案 0 :(得分:2)

您的目的地是文件网址,而不是文件路径。我总是使用:

NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *documentFullPath = [documentsFolder stringByAppendingPathComponent:name];

或者,在Swift 2中:

let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let fileURL = documents.URLByAppendingPathComponent(name)
let documentsFullPath = fileURL.path

答案 1 :(得分:1)

“storePath”似乎是一个URL而不是字符串“path”。添加一些日志 - 我怀疑你不想要“absoluteString”而是“path”。