Chandan Reddy Chandan Reddy - 24 days ago 7x
iOS Question

PHFetchResults date filter not generating correct results for time range

I am trying to fetch images from photo library within the range of two dates and I am getting the images successfully. Using PHAsset Library

Now the problem is that am not able to get images between two times of the same day like between 12:10PM to 12:30PM

Using below code

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;

-- And passing those dates to below method to get images

PHFetchResult *result = [self getAssetsFromLibraryWithStartDate:startDate andEndDate:endDate];

Dates and time coming correct when i print in log but not getting images

How to solve this problem ?


The date created here would be in UTC timezone and yours may vary. Which is why the predicate may not return you correct results.

Make sure you have set the timezone of calendar to your system timezone before creating a date from it like:

NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[gregorian setTimeZone: [NSTimeZone systemTimeZone]];
NSDate *date = [gregorian dateFromComponents:comps];

That will create the date in your local timezone and generate correct results.