iphone - "The operation couldn’ t 完成。 ( cocoa 错误 512。)”

标签 iphone objective-c nsdata

我有这段代码,它应该可以完美地工作,但我不明白为什么它不能:

+(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/

相关文章:

ios - 核心剧情: Show yearly labels on the x-axis for daily values

ios - 如何将 .plist xml 字符串转换为 NSDictionary

ios - 应用程序在 Xcode 9 的 iphone X 模拟器中不占据整个屏幕

objective-c - [NSMutableArray objectAtIndex :]: index 0 beyond bounds for empty array'

ios - 在 CollectionView 的 didSelectItemAtIndexPath 方法中获取 CGPoint

objective-c - 保存到 watchOS 2 文档文件夹

iphone - NSString 转换为 NSMutableData 而不转换为 NSData

python - Objective-C 将 NSData 压缩为 Python gzip 字符串?

iphone - alloc initWithObjects 与 arrayWithObject

iphone - 跳转到UITabBarViewController中的另一个ViewController