问题
I need to know if an image is already in the iOS gallery. I am developing a messaging client app and, in my chat list, I am able to download images/videos of incoming messages when I tap into the image thumbnail.
The issue is, when I tap in the thumbnail, I download and save that image into the iOS photo gallery, but if I tap again I don't want to download and save it again, I want to retrieve it from the photo gallery.
Resuming, I want to look for the image in the photo gallery and retrieve it.
Here is my code to save the image in my custom photo album using ALAssetsLibrary:
[self writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:
^(NSURL* assetURL, NSError* error)
{
if (error!=nil) {
completionBlock(error);
return;
}
//add the asset to the custom photo album
[self addAssetURL: assetURL
toAlbum:albumName
withCompletionBlock:completionBlock];
}
];
-(void)addAssetURL:(NSURL*)assetURL toAlbum:(NSString*)albumName withCompletionBlock:(SaveImageCompletion)completionBlock
{
__block BOOL albumWasFound = NO;
[self enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:
^(ALAssetsGroup *group, BOOL *stop)
{
if ([albumName compare: [group valueForProperty:ALAssetsGroupPropertyName]]==NSOrderedSame) {
albumWasFound = YES;
[self assetForURL: assetURL
resultBlock:
^(ALAsset *asset)
{
//add photo to the target album
[group addAsset: asset];
completionBlock(nil);
} failureBlock: completionBlock
];
return;
}
if (group==nil && albumWasFound==NO) {
//Target album does not exist, create it
__weak ALAssetsLibrary* weakSelf = self;
[self addAssetsGroupAlbumWithName:albumName
resultBlock:
^(ALAssetsGroup *group)
{
[weakSelf assetForURL: assetURL
resultBlock:
^(ALAsset *asset)
{
//add photo to the newly created album
[group addAsset: asset];
completionBlock(nil);
} failureBlock: completionBlock
];
} failureBlock: completionBlock
];
return;
}
} failureBlock: completionBlock
];
}
Maybe with the assetURL I could do it, but I have been searching in Apple's documentation and I didn't see anything.
Thanks!!
回答1:
You can get Asset URL after the save process using completion block. You can retrieve the saved image using this Asset URL.
Unfortunately, you can't check file exist in Photolibrary. The reason behind is, the system will automatically embed many extra information with the image while you save in to Photolibrary. example like location, time etc.. So the binary content will be different for same images.
So, you have only one solution. Save the images into document directory and do a file exist using algorithms like CRC, MD5 etc..
来源:https://stackoverflow.com/questions/21427952/check-if-an-image-is-already-in-gallery-and-retrieve-it