从IOS的专辑中获取今天的照片

时间:2014-10-12 01:12:20

标签: ios photo

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

3 个答案:

答案 0 :(得分:9)

Swift 3版本,包含一系列日期:

HANDLE

答案 1 :(得分:6)

您可以使用此代码段获取今天的照片,该照片适用于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;
    }
}

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

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

答案 2 :(得分:2)

您可以在当天使用谓词

PHFetchOptions *allPhotosOptions = [PHFetchOptions new];
allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

NSPredicate *predicateMediaType = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];
NSDate *date = [[NSDate date] beginningOfDay];
NSPredicate *predicateDate = [NSPredicate predicateWithFormat:@"creationDate >= %@", date];

NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicateDate, predicateMediaType]];


allPhotosOptions.predicate = compoundPredicate;

PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];

其中

@implementation NSDate (Utils)

- (NSDate *)beginningOfDay {
NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [calendar components:CYCalendarUnitYear | CYCalendarUnitMonth | CYCalendarUnitDay fromDate:self];

    return [calendar dateFromComponents:components];
}