3
votes

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.

1
Please add the outputs of the logs.Amin Negm-Awad
There are no logs - it just says. The operation couldn't be completed. Cocoa Error 4.stktrc
I know it's been a while but I had this problem and for me it was because the directory into which I was trying to save a file didn't exist.Rob Sanders
Thanks @RASS! Your suggestion solved this for me.julianwyz
@RASS please put this as a solution. It worked for me tooKunal Balani

1 Answers

2
votes

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:

i.e.

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 _ {

    }
}