And*_*rew 6 iphone objective-c nsdata
我有这个代码,应该是完美的工作,但我不能udnerstand为什么它不是:
+(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;
}
Run Code Online (Sandbox Code Playgroud)
它传递了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"}
Run Code Online (Sandbox Code Playgroud)
任何想法为什么会这样?
在路径中首先写入文件时,我能够重现您的错误@"Documents/Images/",然后尝试使用您的代码编写图像.
我认为有两种可能的情况:
1)您之前执行的应用程序错误地创建了该文件.如果您使用以下菜单重置模拟器,将解决此问题:iOS模拟器>重置内容和设置,以及从您的设备卸载应用程序:长按>单击x符号.
2)您的应用程序中的某个地方有一些代码可以创建此文件.如果是这种情况,您应该找到此代码并将其删除.