从IOS的相册中获取今天的照片

Gao*_*Gao 5 photo ios

有没有办法从ios中的专辑中获取今天的照片?我知道如何获取专辑,但所有照片都显示为时间轴.我只想获得今天的照片或最近两天的照片,我怎么能意识到这一点?谢谢.

Nun*_*ves 10

Swift 3版本,日期范围:

let fromDate = // the date after which you want to retrieve the photos
let toDate // the date until which you want to retrieve the photos 

let options = PHFetchOptions()
options.predicate = NSPredicate(format: "creationDate > %@ && creationDate < %@", fromDate as CVarArg, toDate as CVarArg)

//Just a way to set order
let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false)
options.sortDescriptors = [sortDescriptor]

return PHAsset.fetchAssets(with: .image, options: options)
Run Code Online (Sandbox Code Playgroud)


gab*_*ler 5

您可以使用此片段获取今天的照片,该照片适用于iOS 8.我最初从最近添加的相册中过滤了资产,该相册存储了过去30天的照片或1000张照片.用户有可能在两天内拍摄超过1000张照片,因此我更改了代码以从库中获取所有照片.

PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
options.predicate = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];

PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsWithOptions:options];

//get day component of today
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponent = [calendar components:NSCalendarUnitDay fromDate:[NSDate date]];
NSInteger currentDay = dayComponent.day;

//get day component of yesterday
dayComponent.day = - 1;
NSDate *yesterdayDate = [calendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];
NSInteger yesterDay = [[calendar components:NSCalendarUnitDay fromDate:yesterdayDate] day];

//filter assets of today and yesterday add them to an array.
NSMutableArray *assetsArray = [NSMutableArray array];
for (PHAsset *asset in assetsFetchResult) {
    NSInteger assetDay = [[calendar components:NSCalendarUnitDay fromDate:asset.creationDate] day];

    if (assetDay == currentDay || assetDay == yesterDay) {
        [assetsArray addObject:asset];
    }
    else {
        //assets is in descending order, so we can break here.
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

在iOS 8之前,使用ALAssetsLibrary,假设您有一个照片组,以相反的顺序枚举该组,并执行与上面类似的操作.

[self.photoGroup enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) {
      NSDate *date = [asset valueForProperty:ALAssetPropertyDate];
  }];
Run Code Online (Sandbox Code Playgroud)