在iOS应用中安排任务

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

解决方法

我建议使用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每小时触发一次执行相同的检查,即调用函数.这是为了处理用户在您的应用中花费大量时间的情况.这种方式在一周之后它最终将重新启用,但不一定恰好在正确的时间,但通常是正常的.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...