简体   繁体   中英

The operation couldn’t be completed. Cocoa Error 4

I am having issues on a project i've taken over for a pervious developer that got halfway through and then left - the issues is that on a particular call to save an image from a url into core data it returns the error

The operation couldn't be completed. Cocoa Error 4.

From what I can see error 4 is NSFileNoSuchFileError - the code associated with it is

if (iconURL)
{
    NSURL *imageURL = [NSURL URLWithString:iconURL];
    NSData *img = [NSData dataWithContentsOfURL:imageURL];
    NSString *path = [self logoPath];
    NSLog(@" url path %@", imageURL);

NSError *error = nil;
BOOL success = [img writeToFile:path options:0 error:&error];
if (! success) {
    NSLog(@" purple monkey! %@", [error localizedDescription]);
}
}
else if ([self hasLogo])

{
    NSError *error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:[self logoPath] error:&error];
    if (error)
        NSLog(@"Error removing old logo: %@", [error localizedDescription]);
}

it is throwing the error in the log that conatains the world purple monkey! - The odd thing is that it works in the original project - i have tried carious combinations of simulator, clearing simulator, running on devices etc, and still get the same result..

Thanks Guys.

Here's the solution, due to popular request:

This happens when the directory into which you are trying to save the file doesn't exist. The way to get round it is to put in place checks as you save that create directories that don't already exist:

ie

if (![[NSFileManager defaultManager] fileExistsAtPath:someDirPath]) {
    NSError *error = nil;
    if (![[NSFileManager defaultManager] createDirectoryAtPath:someDirPath withIntermediateDirecotries:YES attributes:nil error:&error]) {
        NSLog(@"Error: %@. %s, %i", error.localizedDescription, __PRETTY_FUNCTION__, __LINE__);
    }
}

EDIT:

Here's the equivalent in Swift:

if !NSFileManager.defaultManager().fileExistsAtPath("path") {
    do {
        try NSFileManager.defaultManager().createDirectoryAtPath("path", withIntermediateDirectories: true, attributes: nil)
    } catch _ {

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM