在iOS应用程序中安排任务

Ard*_*ner 8 ios

我想实现类似于WhatsApp的静音功能的功能.所以基本上,用户停止收到通知(在我的情况下,使用位置管理器)一段时间.在此之后,通知(位置管理器)将自动打开.如何在单击按钮后的一周内安排此类事件(自动打开位置管理器)?

Sam*_*din 6

我建议使用NSTimers的混合方法,并在应用程序启动或到达前台时进行检查.

当用户禁用通知时,将此次存储在NSUserDefaults中作为notificationsDisabledTime.

// Declare this constant somewhere
const NSString *kNotificationDisableTime=@"disable_notifications_time"

[[NSUserDefaults sharedUserDefaults] setObject:[NSDate date] forKey:kNotificationDisableTime];
Run Code Online (Sandbox Code Playgroud)

现在,只要应用程序启动或到达前台,请检查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
    }
}
Run Code Online (Sandbox Code Playgroud)

作为备份,有一个NSTimer每小时触发一次执行相同的检查,即调用此函数.这是为了处理用户在您的应用中花费大量时间的情况.这种方式在一周之后最终会重新启用,但不一定是在正确的时间,但通常情况下也是如此.