我有这段代码,它应该可以完美地工作,但我不明白为什么它不能:
+(NSString *)writeImageToFile:(UIImage *)image {
NSData *fullImageData = UIImageJPEGRepresentation(image, 1.0f);
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Images/"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = NO;
BOOL directoryExists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory];
if (directoryExists) {
NSLog(@"isDirectory: %d", isDirectory);
} else {
NSError *error = nil;
BOOL success = [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
if (!success) {
NSLog(@"Failed to create directory with error: %@", [error description]);
}
}
NSString *name = [NSString stringWithFormat:@"%@.jpg", [JEntry generateUuidString]];
NSString *filePath = [path stringByAppendingPathComponent:name];
NSError *error = nil;
BOOL success = [fullImageData writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (!success) {
NSLog(@"Failed to write to file with error: %@", [error description]);
}
return filePath;
}
它通过了 directoryExists 没有错误,但是当它到达 writeToFile 时,它给了我这个错误:
Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x5634ee0 {NSFilePath=/var/mobile/Applications/5E25F369-9E05-4345-A0A2-381EDB3321B8/Documents/Images/18DAE0BD-6CB4-4244-8ED1-9031393F6DAC.jpg, NSUnderlyingError=0x5625010 "The operation couldn’t be completed. Not a directory"}
知道为什么会这样吗?
最佳答案
当我先在路径 @"Documents/Images/"
中写入文件,然后尝试使用您的代码写入图像时,我能够重现您的错误。
我认为这有两种可能的情况:
1) 您在之前执行应用程序时错误地创建了该文件。如果您使用菜单重置模拟器,这将得到解决:iOS 模拟器 > 重置内容和设置,并从您的设备上卸载该应用程序:长按 > 单击 x 符号.
2) 在您的应用程序的其他地方有一些代码创建了这个文件。如果是这种情况,您应该找到此代码并将其删除。
关于iphone - "The operation couldn’ t 完成。 ( cocoa 错误 512。)”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9547894/