0

我想将文件从应用程序 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"}

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

有任何想法吗 ?

谢谢

4

2 回答 2

2

您的目标是文件 URL,而不是文件路径。我总是使用:

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
于 2012-08-05T19:57:36.470 回答
1

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

于 2012-08-05T19:47:03.600 回答