错误域= NSCocoaErrorDomain代码= 512“操作无法完成。操作无法完成。是目录

时间:2013-01-10 00:12:30

标签: ios ios5 nsdata

我想使用writeToFile将pic图像存储到文档中,但是找到下面的错误,如何解决?

错误Domain = NSCocoaErrorDomain Code = 512“操作无法完成。(Cocoa错误512.)”{NSFilePath = / Users / alexqdh / Library / Application Support / iPhone Simulator / 6.0 / Applications / xxx /Documents/girl.png,NSUnderlyingError = 0x753e630“操作无法完成。目录是”}

-(NSString*)getImagePath:(NSString *)name
{
    NSArray *path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
    NSString *docPath = [path objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *finalPath = [docPath stringByAppendingPathComponent:name];
    [fileManager createDirectoryAtPath:finalPath withIntermediateDirectories:YES attributes:nil error:nil];
    return finalPath;
}
//below is how to use NSData writeToFile
AFImageRequestOperation *opera = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
    img.image = image;
    [self.view addSubview:img];
    NSData *imageData = UIImagePNGRepresentation(img.image);
    if(imageData == nil)
    {
        NSLog(@"imageData nil");
    }
    NSString *picPath = [self getImagePath:@"girl.png"];
    NSLog(@"path:%@",picPath);
    NSError *error = [[NSError alloc]init];
    BOOL a = [imageData writeToFile:picPath options:NSDataWritingAtomic error:&error];
    if(a == YES)
    {
        NSLog(@"YES");
    }
    else
    {
        NSLog(@"NO.error:%@", error);
    }

    /*NSData *imageData = UIImagePNGRepresentation(img.image);
    NSString *picPath = [self getImagePath:@"girl.png"];
    [imageData writeToFile:picPath atomically:YES];*/

    NSLog(@"Got it.code:%d",response.statusCode);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
    NSLog(@"Failed pic.error:%@",error);
}];

[opera start];

1 个答案:

答案 0 :(得分:6)

问题是由创建具有图像名称的目录,然后尝试编写文件来代替目录引起的。换句话说,您首先要创建一个名为:

的目录
  

文档/ girl.png /

然后你尝试将文件写入路径:

  

文档/ girl.png

显然这不是你想要做的。在getImagePath:方法中,删除调用以创建目录。 Documents目录已存在。当然,您不需要与文件名对应的目录。

另一个选择是将getImagePath:更改为:

- (NSString*)getImagePath:(NSString *)name {
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
    NSString *docPath = [path objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *finalPath = [docPath stringByAppendingPathComponent:name];

    // Remove the filename and create the remaining path
    [fileManager createDirectoryAtPath:[finalPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];

    return finalPath;
}

此更新后的代码现在支持您传入包含您可能需要的子目录的name值。