문제

How can I fire a UILocalNotification two days before a given NSDate?

도움이 되었습니까?

해결책

Assuming eventDate is the date you have:

NSDate* twoDaysEarlyDate = [[NSDate alloc] initWithTimeInterval:-(86400 * 2) sinceDate:eventDate];

That ignores any possible daylight saving change happening just before the eventDate, which is probably fine for a local notification.

An alternate method if you need to take DST changes into effect would be similar to:

NSCalendar* currentCalendar = [NSCalendar currentCalendar];
NSDateComponents* offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-2];
NSDate* twoDaysEarlyDate = [currentCalendar dateByAddingComponents:offsetComponents toDate:eventDate options:0];

Either option works depending on your needs.

다른 팁

Suppose given date is 'expirationDate' and 'twoDaysBeforeExpirationDate' is the desired date to fire UILocalNotification. Then

NSDate* expirationDate=nil;
NSDate *twoDaysBeforeExpirationDate = [expirationDate dateBySubtractingRequiredDays:2];


- (NSDate *) dateBySubtractingRequiredDays: (NSInteger) dDays
{
    return [self dateByAddingDays: (dDays * -1)];
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top