iOS8之前的
-(void)getiOS8LastImage{
PHAsset *asset = [PHAsset latestAsset];
PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
[imageManager requestImageForAsset:asset targetSize:CGSizeZero contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
if (result) {
_imgV.image = result;
[self showSuitFrame:_imgV img:result];
}
}];
}
实现
@implementation PHAsset (PFLast)
+ (PHAsset *)latestAsset {
// 获取所有资源的集合,并按资源的创建时间排序
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
return [assetsFetchResults firstObject];
}
iOS8之后的
-(void)getPreiOS8LastImage{
ALAssetsLibrary *al = [[ALAssetsLibrary alloc] init];
[al latestAsset:^(ALAsset * _Nullable asset, NSError * _Nullable error) {
NSString *type = [asset valueForProperty:ALAssetPropertyType];
if ([type isEqual:ALAssetTypePhoto]){
UIImage *needImage = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
if (needImage) {
_imgV.image = needImage;
[self showSuitFrame:_imgV img:needImage];
}
}
}];
}
实现
@implementation ALAssetsLibrary (PFLast)
- (void)latestAsset:(void (^)(ALAsset * _Nullable, NSError *_Nullable))block {
[self enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
[group enumerateAssetsWithOptions:NSEnumerationReverse/*遍历方式*/ usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result) {
if (block) {
block(result,nil);
}
*stop = YES;
}
}];
*stop = YES;
}
} failureBlock:^(NSError *error) {
if (error) {
if (block) {
block(nil,error);
}
}
}];
}
@end
#pragma mark - 根据image调整UIImageView的大小
-(void)showSuitFrame:(UIView *)theView img:(UIImage *)img{
CGFloat width = img.size.width;
CGFloat height = img.size.height;
if (width>height) {//宽不变
CGRect frame = theView.frame;
frame.size.height = (CGFloat)theView.frame.size.height*(height/width);
theView.frame = frame;
}else if(width<height){//高不变
CGRect frame = theView.frame;
frame.size.width = (CGFloat)theView.frame.size.width*(width/height);
theView.frame = frame;
}else{//都不变
}
}