我想实现一个类似于 WhatsApp 的静音功能的功能。所以基本上,用户在一段时间内停止接收通知(在我的例子中,使用位置管理器)。在那之后,通知(位置管理器)会自动打开。我如何安排这样的事件(自动打开位置管理器),例如在我单击按钮后 1 周?
最佳答案
我会建议使用 NSTimers 的混合方法,并在应用启动或进入前台时进行检查。
当用户禁用通知时,将此时间存储在 NSUserDefaults 中作为 notificationsDisabledTime。
// Declare this constant somewhere
const NSString *kNotificationDisableTime=@"disable_notifications_time"
[[NSUserDefaults sharedUserDefaults] setObject:[NSDate date] forKey:kNotificationDisableTime];
现在,每当应用程序启动或进入前台时,检查是否 notificationsDisabledTime 和当前时间之间的持续时间大于一周。如果是这样,请重新启用通知。将其包装在一个很好的可重用函数中。在 app delegate 中调用此函数,applicationDidBecomeActive:
-(void)reenableNotificationsIfNecessary {
if ( notifications are already enabled ... ) {
return;
}
NSDate *disabledDate = [[NSUserDefaults sharedUserDefaults] objectForKey:kNotificationDisableTime]
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:disabledDate
toDate:[NSDate date] options:0];
NSInteger days = [components day];
if(days >7) {
// re-enable notifications
}
}
作为备份,有一个 NSTimer 大约每小时触发一次,执行相同的检查,即调用此函数。这是为了处理用户在您的应用中花费大量时间的情况。这样一星期后它最终会重新启用,虽然不一定在正确的时间,但通常没问题。
关于ios - 在 iOS 应用程序中安排任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32248222/