开发者

What's wrong with my copy here?

I'm trying to copy a file from my application bundle to my app's documents directory. I'm getting an error, "Cocoa Error 262". What am I doing wrong? Here's my code:

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData.sqlite"];
NSURL *initialURL = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"CoreData" ofType:@"sqlite"]];

NSError *error = nil;

if (![[NSFileManager defaultManager] fileExistsAtPath:[initialURL absoluteString]]) {
    NSLog(@"Original does not exist. \nPath: %@", [initialURL absoluteString]);
}  

if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL absoluteString]]) {
    NSLog(@"Destination file does not exist.开发者_如何学编程 \nPath: %@", [storeURL absoluteString]);

    [[NSFileManager defaultManager] copyItemAtURL:initialURL toURL:storeURL error:&error];

    NSLog(@"Error: %@", [error description]);
}


The problem is you're initializing a URL with a plain old file path.

NSURL *initialURL = 
    [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"CoreData" 
                                                         ofType:@"sqlite"]];

Use [NSURL fileURLWithPath:] instead.


The error you are getting is

NSFileReadUnsupportedSchemeError Read error because the specified URL scheme is unsupported

which I believe would mean one of your paths is not forming correctly. perhaps write these paths to the log and see if they are coming out as you expect them to.


I've solved the problem, although to be honest, I'm not sure what it was. I have to go over the working code again, but here it is:

    NSError *error = nil;


NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", @"CoreData", @"sqlite"]];

//if file does not exist in document directory, gets original from mainbundle and copies it to documents.

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    NSString *defaultFilePath = [[NSBundle mainBundle] pathForResource:@"CoreData" ofType:@"sqlite"];
    [[NSFileManager defaultManager] copyItemAtPath:defaultFilePath toPath:filePath error:&error];

    if (error != nil) {
        NSLog(@"Error: %@", error);
    }
}

Edit:

I suspect that the path to the application directory was incorrect, given that the body of the generated applicationDocumentsDirectory looks different than the method used for the value of the documentsDorectory variable shown above.


Error 262 is defined in FoundationErrors.h to be NSFileReadUnsupportedSchemeError.

I'd suggest that you use NSLog() to write out the literal values of the two URLs that you're using and make sure that they are file:// URLs and that they look complete.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜