類似于微信發(fā)送最新圖片和QQ空間獲取最近的照片功能的實現(xiàn)(iOS 8 以上)
先導入頭文件 <Photos/Photos.h>
判斷系統(tǒng)相冊權(quán)限是否開啟:
/*
typedef NS_ENUM(NSInteger, PHAuthorizationStatus) {
PHAuthorizationStatusNotDetermined = 0,用戶尚未做出了選擇這個應用程序的問候
PHAuthorizationStatusRestricted,此應用程序沒有被授權(quán)訪問的照片數(shù)據(jù)恩静『洳担可能是家長控制權(quán)限。
PHAuthorizationStatusDenied,用戶已經(jīng)明確否認了這一照片數(shù)據(jù)的應用程序訪問.
PHAuthorizationStatusAuthorized用戶已授權(quán)應用訪問照片數(shù)據(jù).
}
*/
PHAuthorizationStatus photosAuthStatus = [PHPhotoLibrary authorizationStatus];
if(photosAuthStatus ==PHAuthorizationStatusRestricted|| photosAuthStatus ==PHAuthorizationStatusDenied){
NSString*errorStr =@"應用相冊權(quán)限受限,請在設置中啟用";
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小時之內(nèi)的
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(@"沒有查詢到數(shù)據(jù)");
}else{
NSLog(@"一個小時以內(nèi)的圖片一共%ld張",result.count);
PHAsset* asset = [resultlastObject];
[selfgetImageWithAsset:assetwithBlock:^(UIImage*image) {
self.SlectedImage.image= image;
}];
}
asset 轉(zhuǎn)換成image
//獲取image
- (void)getImageWithAsset:(PHAsset*)asset withBlock:(void(^)(UIImage*image))block{
//通過asset資源獲取圖片
[[PHCachingImageManagerdefaultManager]requestImageForAsset:assettargetSize:PHImageManagerMaximumSizecontentMode:PHImageContentModeAspectFitoptions:nilresultHandler:^(UIImage*_Nullableresult,NSDictionary*_Nullableinfo) {
block(result);
}];
}