سؤال

I am implementing UILocalNotification to remind the first-time user at 8:00 PM to use the app again. The user can switch it completely off or setup a different time.

I picked 8:00 PM as time after work, so that it is less interrupting or intrusive.

I am not sure how to handle timezones.

If the user is in New York. [NSDate date] only returns a GMT datetime (a moment in time since the reference date). So how do I determine his 8:00 pm?

Could I just do this?

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

NSDateComponents *dateComps = [calendar components:(NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitTimeZone) fromDate:[NSDate date]];

[dateComps setHour:20];
[dateComps setTimeZone:[NSTimeZone defaultTimeZone]];

NSDate *result = [calendar dateFromComponents:dateComps];
هل كانت مفيدة؟

المحلول

From the UILocalNotification docs:

The date specified in fireDate is interpreted according to the value of this property. If you specify nil (the default), the fire date is interpreted as an absolute GMT time, which is suitable for cases such as countdown timers. If you assign a valid NSTimeZone object to this property, the fire date is interpreted as a wall-clock time that is automatically adjusted when there are changes in time zones; an example suitable for this case is an an alarm clock.

So to ensure your notification is set at the same 'wall-clock' time (eg 8pm) regardless of the time zone, just do

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = theDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top