类似于微信发送最新图片和QQ空间获取最近的照片功能的实现(iOS 8 以上)
先导入头文件 <Photos/Photos.h>
判断系统相册权限是否开启:
/*
typedef NS_ENUM(NSInteger, PHAuthorizationStatus) {
PHAuthorizationStatusNotDetermined = 0,用户尚未做出了选择这个应用程序的问候
PHAuthorizationStatusRestricted,此应用程序没有被授权访问的照片数据。可能是家长控制权限。
PHAuthorizationStatusDenied,用户已经明确否认了这一照片数据的应用程序访问.
PHAuthorizationStatusAuthorized用户已授权应用访问照片数据.
}
*/
PHAuthorizationStatus photosAuthStatus = [PHPhotoLibrary authorizationStatus];
if(photosAuthStatus ==PHAuthorizationStatusRestricted|| photosAuthStatus ==PHAuthorizationStatusDenied){
NSString*errorStr =@"应用相册权限受限,请在设置中启用";
UIAlertController*alter = [UIAlertControlleralert ControllerWithTitle:@"提示"message:errorStrpreferredStyle:UIAlertControllerStyleAlert];
[alteraddAction:[UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]options:@{} completionHandler:nil];
}]];
[self presentViewController:alter animated:YES completion:nil];
return;
}
开始查询图片
PHFetchOptions* options = [[PHFetchOptions alloc]init];
options.sortDescriptors=@[[NSSortDescriptor sortDescriptorWithKey:@"creationDate"ascending:YES]];
//多媒体类型的渭词
NSPredicate* media = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];
//查询1小时之内的
NSDate*date = [NSDatedate];
NSDate*lastDate = [date initWithTimeIntervalSinceNow:-3600];
NSPredicate*predicateDate = [NSPredicate predicateWithFormat:@"creationDate >= %@", lastDate];
//
NSCompoundPredicate*compoundPredicate = [NSCompoundPredicateandPredicateWithSubpredicates:@[media, predicateDate]];
//
options.predicate= compoundPredicate;
PHFetchResult* result = [PHAssetfetchAssetsWithMediaType:PHAssetMediaTypeImageoptions:options];
if(result.count==0) {
NSLog(@"没有查询到数据");
}else{
NSLog(@"一个小时以内的图片一共%ld张",result.count);
PHAsset* asset = [resultlastObject];
[selfgetImageWithAsset:assetwithBlock:^(UIImage*image) {
self.SlectedImage.image= image;
}];
}
asset 转换成image
//获取image
- (void)getImageWithAsset:(PHAsset*)asset withBlock:(void(^)(UIImage*image))block{
//通过asset资源获取图片
[[PHCachingImageManagerdefaultManager]requestImageForAsset:assettargetSize:PHImageManagerMaximumSizecontentMode:PHImageContentModeAspectFitoptions:nilresultHandler:^(UIImage*_Nullableresult,NSDictionary*_Nullableinfo) {
block(result);
}];
}