iOS8.0+获取相册最近的一张图片
2017-07-05 本文已影响3547人
_moses
引入头文件#import <Photos/Photos.h>
.h文件,声明方法
/**
获取相册最近的一张图片
@param screenshot 获取相册最近的一张截屏
@param imageBlock 得到图片
*/
+ (void)getCurrentImage:(BOOL)screenshot callBack:(void (^)(UIImage *image))imageBlock;
.m文件,实现方法
+ (void)getCurrentImage:(BOOL)screenshot callBack:(void (^)(UIImage *))imageBlock {
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
NSLog(@"相册权限未开放");
return;
}
// 获取最近的照片
PHAsset *asset = [[PHAsset fetchAssetsWithOptions:[PHFetchOptions new]] lastObject];
if (screenshot) {
// 获取屏幕快照相册
PHAssetCollection *assetCollection = [[PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumScreenshots options:nil] firstObject];
// 获取最近的屏幕快照
asset = [[PHAsset fetchAssetsInAssetCollection:assetCollection options:[PHFetchOptions new]] lastObject];
}
if (!asset) {
NSLog(@"相册里没有照片");
return;
}
long long now = [[NSDate date] timeIntervalSince1970];
long long creatTime = [asset.creationDate timeIntervalSince1970];
if ((now - creatTime) > 86400) {
NSLog(@"最新的照片是一天以前的");
return;
}
CGSize targetSize = [UIScreen mainScreen].bounds.size;
NSInteger index = targetSize.width == 414 ? 3 : 2;
// 将PHAsset *类型的图片转成UIImage *类型
[[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
if (result && result.size.width == targetSize.width * index && result.size.height == targetSize.height * index && imageBlock) {
imageBlock(result);
}
}];
}