[英]The operation couldn’t be completed. Cocoa Error 4
我在一个项目上遇到了问题,我已经接手了一个上半身然后离开的前任开发人员 - 问题是在特定的调用中将图像从url保存到核心数据中它返回错误
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]);
}
它在日志中抛出了错误世界紫猴! - 奇怪的是它在原始项目中有效 - 我尝试了模拟器,清除模拟器,在设备上运行等的龋齿组合,并且仍然得到相同的结果..
多谢你们。
由于受欢迎的要求,这是解决方案:
当您尝试保存文件的目录不存在时,会发生这种情况。 绕过它的方法是在保存时创建检查,创建尚不存在的目录:
即
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 _ {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.