Recently, the company has a requirement to cache the photos to be sent in the message and display the photos directly when opening the viewController next time. The idea is to save the PHAsset when you exit the viewController and load the image through the PHAsset the next time you open that viewController.
Baidu only found the localIdentifier that said PHAsset needs to be stored. In fact, I was very confused after reading it. No one listed the code to explain the specific practice. Here’s how I do it.
In the beginning, I did store phassets with localidentifiers.
If you click on the PHAsset header file, you will see that there is no localIdentifier. If you click on the parent class, which is PHObject, you will see that there is.
First we need to save the localIdentifier(how to store NSString is not discussed here):
NSString *localIdentifier = asset.localIdentifier; // Local storageCopy the code
There’s no question about saving this string, and then how do you use it next time?
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[str] options:nil];
PHAsset *asset = fetchResult.firstObject;
Copy the code
This code returns a PHAsset based on the localIdentifier, but first returns an object of type PHFetchResult. Click on the header file:
@interface PHFetchResult<ObjectType> : NSObject <NSCopying, NSFastEnumeration>
Copy the code
You can see that it implements the NSCopying and NSFastEnumeration protocols, which means it can use fast enumeration and copy methods, and it looks like an array from its properties.
+ (PHFetchResult<PHAsset *> *)fetchAssetsWithLocalIdentifiers:(NSArray<NSString *> *)identifiers options:(nullable PHFetchOptions *)options;
Copy the code
Because this method is passing in an array of string generics, I’m actually getting a PHAsset by passing one in.
so
PHAsset *asset = fetchResult.firstObject;
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.synchronous = YES;
[[PHImageManager defaultManager]requestImageForAsset:asset targetSize:CGSizeMake(asset.pixelWidth, asset.pixelHeight) contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
[photos addObject:result];
}];
Copy the code
Use the code above to get your last photo again through PHAsset.
One final point: Sometimes users delete photos from their phones. If the deleted photos contain phassets stored in the APP, this situation requires error handling, or it could cause a crash. In this case PHFetchResult fetchAssetsWithLocalIdentifiers this method to return to the use of the empty, so the prognosis can be:
PHAsset *asset = fetchResult.firstObject; if (! Asset) {// Handle photo deletion}Copy the code