在iOS应用中安排任务
我想实现类似于WhatsApp的静音function的function。 所以基本上,用户停止收到通知(在我的情况下,使用位置管理器)一段时间。 在此之后,通知(位置管理器)将自动打开。 如何在单击按钮后的一周内安排此类事件(自动打开位置管理器)?
我建议使用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每小时触发一次执行相同的检查,即调用此函数。 这是为了处理用户在您的应用中花费大量时间的情况。 这种方式在一周之后它最终将重新启用,但不一定恰好在正确的时间,但通常是正常的。
1.方法我建议使用NSTimer Class并设置一个定时器来调用将取消静音的function。 还有在后台使用方法的后台任务,可以通过添加来完成
var bgTask = UIBackgroundTaskIdentifier var app = UIApplication.sharedApplication() app.beginBackgroundTaskWithExpirationHandler { () -> Void in app.endBackgroundTask(bgTask) }
在呼叫时间表之前
例如,我想静音8小时,而不是你需要打电话
NSTimer.scheduledTimerWithTimeInterval(60*8, target:(self), selector: Selector("stopper"), userInfo: nil, repeats: no);
并添加你的stopper
func stopper(){ //unmute }
您也可以通过将userInfo
添加到计时器来发送有关将被静音的对象的特定信息。
2.方法
您可以查看applicationDidEnterBackground
和applicationDidEnterForeground
之间的时差
let date = NSDate.date()
和差值let difference NSDate.timeIntervalSinceDate(date)