У меня есть приложение iOS, которое порой должно локально хранить объекты UIImage.writeToFile не работает после removeItemAtPath
Я использую [UIImagePNGRepresentation(image) writeToFile:full_path options:NSAtomicWrite error:nil];
, чтобы сохранить изображение и [file_manager removeItemAtPath:full_path error:NULL];
, чтобы удалить файл.
Все это прекрасно работает, однако, всякий раз, когда я удаляю файл, должен ли я решить сохранить новый файл (который, как раз так, имеет то же имя, что и старый файл), код сохранения не работает и возвращает следующее сообщение об ошибке:
: ImageIO: CGImageReadCreateDataWithMappedFile 'open' failed error = 2 (No such file or directory)
: ImageIO: CGImageReadCreateDataWithMappedFile 'open' failed error = 2 (No such file or directory)
: ImageIO: PNG zlib error
так Вот что я не понимаю, почему я не могу сохранить файл с тем же именем, что и старый файл, после того, как я удалил старый файл?
Причина, по которой я спрашиваю об этом, заключается в том, что мое приложение будет сохранять определенные файлы изображений, а затем, когда они больше не понадобятся, мое приложение удалит их. Однако есть моменты, когда моему приложению нужны файлы изображений снова (может быть через несколько часов после удаления или несколько недель). Когда это произойдет, мое приложение загрузит соответствующие данные изображения, а затем попытается сохранить его. И это происходит при возникновении ошибки.
Что-то не так?
Спасибо за ваше время, Дэн.
ОБНОВЛЕНИЕ - Вот методы, у меня есть настройки для сохранения/доступа и удалять мои файлы изображений
-(void)save_local_image:(UIImage *)image :(NSString *)file_name {
// Get the app documents directory link.
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// Add the new file name to the link.
NSString *database_link = [[NSString alloc] initWithString:[documents stringByAppendingPathComponent:file_name]];
// Save the image data locally.
[UIImagePNGRepresentation(image) writeToFile:database_link options:NSAtomicWrite error:nil];
}
-(UIImage *)get_local_image:(NSString *)file_name {
// Create the return data.
UIImage *image_data = nil;
// Get the app documents directory.
NSArray *directory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] error:NULL];
// Only check for data if at least
// one file has been saved locally.
if ([directory count] > 0) {
// Loop through the different local files.
for (NSString *path in directory) {
// Get the full local file URL.
NSString *full_path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:path];
// Get the range of the file name.
NSRange range = [full_path rangeOfString:file_name];
// Get the image data if it exists.
if ((range.location != NSNotFound) || (range.length == [file_name length])) {
// Load the image file in.
image_data = [UIImage imageWithContentsOfFile:full_path];
break;
}
}
}
return image_data;
}
-(void)delete_local_image:(NSString *)file_name {
// Get the app documents directory.
NSArray *directory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] error:NULL];
// Only check for data if at least
// one file has been saved locally.
if ([directory count] > 0) {
// Loop through the different local files.
for (NSString *path in directory) {
// Get the full local file URL.
NSString *full_path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:path];
// Get the range of the file name.
NSRange range = [full_path rangeOfString:file_name];
// Delete the local image data if it exists.
if ((range.location != NSNotFound) || (range.length == [file_name length])) {
NSError *testError = nil;
// Delete the image file.
NSFileManager *file_manager = [[NSFileManager alloc] init];
BOOL success = [file_manager removeItemAtPath:full_path error:&testError];
NSLog(@"%d", success);
if (testError != nil) {
NSLog(@"%@", testError.localizedDescription);
}
break;
}
}
}
}
Привет, что Возврат файла «- (BOOL) fileExistsAtPath: (NSString *)» перед удалением файла? – Estevex
@Estevex Я даже не проверяю это, я просто использую NSRange, чтобы узнать, существует ли файл. Я обновил свой вопрос с помощью своего кода. Если вы прокрутите код вниз, вы увидите мой метод удаления файла. – Supertecnoboff
Вы хотите сохранить изображение, которое вы только что удалили? Возможно, 'UIImagePNGRepresentation' пытается загрузить изображение. – Willeke