PHFetchResults 日期过滤器没有为时间范围生成正确的结果
PHFetchResults date filter not generating correct results for time range
我正在尝试从照片库中获取两个日期范围内的图像 使用 PHAsset 库
现在的问题是我无法在同一天的两次之间获取图像,比如在 12:10PM 到 12:30PM
之间
使用下面的代码
NSDate *startDate = [self getDateForDay:30 andMonth:9 andYear:2016 andHour:12 andMinute:10 andSecond:0];
NSDate *endDate = [self getDateForDay:30 andMonth:9 andYear:2016 andHour:12 andMinute:30 andSecond:0];
--
-(NSDate*) getDateForDay:(NSInteger) day andMonth:(NSInteger) month andYear:(NSInteger) year andHour:(NSInteger) hour andMinute:(NSInteger) minute andSecond:(NSInteger) second{
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:day];
[comps setMonth:month];
[comps setYear:year];
[comps setHour:hour];
[comps setMinute:minute];
[comps setSecond:second];
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *date = [gregorian dateFromComponents:comps];
return date;
}
-- 并将这些日期传递给下面的方法来获取图像
PHFetchResult *result = [self getAssetsFromLibraryWithStartDate:startDate andEndDate:endDate];
当我在日志中打印但未获取图像时日期和时间正确
如何解决这个问题?
此处创建的日期将采用 UTC 时区,您的日期可能会有所不同。这就是为什么谓词可能不会 return 你正确的结果。
确保在从日历创建日期之前将日历的时区设置为系统时区,例如:
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[gregorian setTimeZone: [NSTimeZone systemTimeZone]];
NSDate *date = [gregorian dateFromComponents:comps];
这将创建您当地时区的日期并生成正确的结果。
我正在尝试从照片库中获取两个日期范围内的图像
现在的问题是我无法在同一天的两次之间获取图像,比如在 12:10PM 到 12:30PM
之间使用下面的代码
NSDate *startDate = [self getDateForDay:30 andMonth:9 andYear:2016 andHour:12 andMinute:10 andSecond:0];
NSDate *endDate = [self getDateForDay:30 andMonth:9 andYear:2016 andHour:12 andMinute:30 andSecond:0];
--
-(NSDate*) getDateForDay:(NSInteger) day andMonth:(NSInteger) month andYear:(NSInteger) year andHour:(NSInteger) hour andMinute:(NSInteger) minute andSecond:(NSInteger) second{
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:day];
[comps setMonth:month];
[comps setYear:year];
[comps setHour:hour];
[comps setMinute:minute];
[comps setSecond:second];
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *date = [gregorian dateFromComponents:comps];
return date;
}
-- 并将这些日期传递给下面的方法来获取图像
PHFetchResult *result = [self getAssetsFromLibraryWithStartDate:startDate andEndDate:endDate];
当我在日志中打印但未获取图像时日期和时间正确
如何解决这个问题?
此处创建的日期将采用 UTC 时区,您的日期可能会有所不同。这就是为什么谓词可能不会 return 你正确的结果。
确保在从日历创建日期之前将日历的时区设置为系统时区,例如:
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[gregorian setTimeZone: [NSTimeZone systemTimeZone]];
NSDate *date = [gregorian dateFromComponents:comps];
这将创建您当地时区的日期并生成正确的结果。