案例:如果您将时间设置为上午8:00,将天设置为周一和周三,那么我们会在周一和周三上午8:00通知用户。处理这种情况的最佳方法是什么。
到目前为止,我搜索了UILocalNotofication和NSTimer。还有其他需要处理的事情吗?
答案 0 :(得分:0)
这个关于如何使用UILocalNotification
- (void)scheduleAlarmForDate:(NSDate*)theDate
{
UIApplication* app = [UIApplication sharedApplication];
NSArray* oldNotifications = [app scheduledLocalNotifications];
// Clear out the old notification before scheduling a new one.
if ([oldNotifications count] > 0)
[app cancelAllLocalNotifications];
// Create a new notification.
UILocalNotification* alarm = [[UILocalNotification alloc] init];
if (alarm)
{
alarm.fireDate = theDate;
alarm.timeZone = [NSTimeZone defaultTimeZone];
alarm.repeatInterval = 0;
alarm.soundName = @"alarmsound.caf";
alarm.alertBody = @"Time to wake up!";
[app scheduleLocalNotification:alarm];
}
}
Apple不允许你在后台运行NSTimers(存在一些安全问题),这个Apple Guide解释了如何在后台运行任务并有一些代码示例,如上所述。 / p>
答案 1 :(得分:0)
我已阅读其他设置闹钟的方法in this blog
否则,我认为你必须使用通知。
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit| NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: now];
[componentsForFireDate setWeekday: 2] ;
[componentsForFireDate setHour: 8] ;
[componentsForFireDate setMinute:0] ;
[componentsForFireDate setSecond:0] ;
NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForFireDate];
UILocalNotification *notification = [[UILocalNotification alloc] init] ;
notification.fireDate = fireDateOfNotification ;
notification.timeZone = [NSTimeZone localTimeZone] ;
notification.alertBody = [NSString stringWithFormat: @"Hi!"] ;
notification.userInfo= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Updates added for that week!"] forKey:@"subtitle"];
notification.repeatInterval= NSWeekCalendarUnit ;
notification.soundName=UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification] ;