我在一个项目上遇到了问题,我接手了一个过去一半然后离开的前任开发人员 - 问题是在特定调用中将图像从url保存到核心数据中它返回错误< / p>
The operation couldn't be completed. Cocoa Error 4.
从我所看到的错误4是NSFileNoSuchFileError - 与之关联的代码是
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]);
}
它在日志中抛出了包含世界紫色猴子的错误! - 奇怪的是它在原始项目中有效 - 我尝试了模拟器,清除模拟器,在设备上运行等的狡猾组合,并且仍然得到相同的结果..
谢谢大家。
答案 0 :(得分:2)
由于受欢迎的要求,这是解决方案:
当您尝试保存文件的目录不存在时,会发生这种情况。绕过它的方法是在保存时创建检查,以创建尚不存在的目录:
即
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__);
}
}
编辑:
这是Swift中的等价物:
if !NSFileManager.defaultManager().fileExistsAtPath("path") {
do {
try NSFileManager.defaultManager().createDirectoryAtPath("path", withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
}