ios - 在 iOS 应用程序中安排任务

标签 ios

我想实现一个类似于 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/

相关文章:

ios - 在 iOS 7 中更新约束后获取 "Unable to simultaneously satisfy constraints"

ios - 错误您必须初始化 PFFacebookUtils

ios - 如何将结构参数与 OCMock 匹配?

cocoa - 经验丰富的 iOS 开发人员开始 OS X 开发的最佳实践和建议?

ios - 禁用手势以下拉表单/页面模式呈现

ios - 位置 : fixed and width 100% in ios

ios - 放大 UIView 而不会像素化

ios - UIViewControllerView 内的 UITableView 意外边距

ios - 如何在 iOS 4.3/5 中手动循环播放 html5 视频?

objective-c - 应用程序打开时出现黑屏