Obj-C检查图片库中是否已经存在图片

在我的应用程序,我必须实现保存图像function。 我已经节省了这样的:

UIImage *image = [UIImage imageNamed:actualBackground]; UIImageWriteToSavedPhotosAlbum( image, self, @selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:), nil); /* ... */ - (void)thisImage:(UIImage *)image hasBeenSavedInPhotoAlbumWithError:(NSError *)error usingContextInfo:(void *)ctxInfo { if (!error){ UIImagePickerController *picker = [[UIImagePickerController alloc] init]; [self presentViewController:picker animated:YES completion:nil]; } } 

不幸的是,我必须检查文件是否已经存在,以防止冗余保存。 此外,这是必要的,因为多次保存相同的图像不会覆盖一个文件,但它创build它的副本…

你知道如何解决这个问题吗?

解:

根据Shravya Boggarapu答案我将assetUrl存储在我的NSUserDefaults 。 完整的代码:

 - (IBAction)onDownloadClick:(UIButton *)sender { UIImage *image = [UIImage imageNamed:actualBackground]; NSString *key = [NSString stringWithFormat:@"assetsUrl %@", actualBackground]; NSString *savedValue = [[NSUserDefaults standardUserDefaults] stringForKey:key]; NSURL *url = [NSURL URLWithString:savedValue]; if (url != nil) { PHFetchResult *fetch = [PHAsset fetchAssetsWithALAssetURLs:[NSArray arrayWithObject:url] options:nil]; if ([fetch count]) { UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"Already downloaded", nil) delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [myAlert show]; return; } } ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) { [library assetForURL:assetURL resultBlock:^(ALAsset *asset) { NSLog(@"assetURL %@", assetURL); NSString *ass = [assetURL absoluteString]; [[NSUserDefaults standardUserDefaults] setObject:ass forKey:key]; [[NSUserDefaults standardUserDefaults] synchronize]; UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString( @"Image downloaded", nil) delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [myAlert show]; } failureBlock:^(NSError *error){ }]; }]; } 

希望它会帮助别人。

我有一个解决scheme,但不适用于所有情况。

将图像保存到相机胶卷的事情是,当您将图像添加到相机胶卷时,会创build一个assetURL。 此外,这个资产的URL每次都是新的,所以如果你保存到相机胶卷,它会创build一个副本。 图像的名称也不被保留。

如果图像首先通过您的应用程序添加到相机胶卷中,则可以将assetURL作为图像信息的一部分进行存储。

在我的应用程序中,每个包含一些关键信息的图像都会保留一个字典。 这包括图像的assetURL,如果它保存到相机胶卷。

一旦你有了URL,你可以使用fetchAssetsWithALAssetURLs:options: function来检查它的存在。

如果URL为零,或者提取的资产为零,则意味着相机胶卷中不存在图像。 所以你可以添加一个新的。

没有简单的方法来比较两个图像,如果你发现一个任务繁重,而不是这个,我们可以比较图像的元数据,我们可以把它写入图像,也可以从图像中读取。

你可以使用这个回购

而且ALAssetLibrary也有一些属性来访问图像元信息。 如果你谷歌与此,你会狡猾得到一些。

像这个