在iOS应用中安排任务 [英] Scheduling a task in an iOS app

查看:91
本文介绍了在iOS应用中安排任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to implement a feature similar to WhatsApp's mute feature. So basically, user stops getting notifications (in my case, using Location Manager) for some time. After that time, notifications (Location Manager) is turned on automatically. How can I schedule such an event (Turning on location manager automatically) for example 1 week after I click a button?

推荐答案

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

I would suggest a hybrid approach using both NSTimers and a check whenever the app launches or comes to the foreground.

当用户禁用通知时,这次存储在NSUserDefaults中为notificationsDisabledTime。 / p>

When the user disables notifications store this time in NSUserDefaults as notificationsDisabledTime.

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

[[NSUserDefaults sharedUserDefaults] setObject:[NSDate date] forKey:kNotificationDisableTime];

现在每当应用程序启动或到达前台时,检查notificationDisabledTime之间的
持续时间当前时间大于一周。如果是,请重新启用通知。用一个很好的可重用函数包装它。在app delegate,applicationDidBecomeActive中调用此函数:

Now whenever the app is launched or comes to the foreground , check whether duration between notificationsDisabledTime and current time is greater than one week. If so re-enable the notifications. Wrap this up in a nice reusable function. Call this function in 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每小时触发一次执行相同的检查,即调用此函数。这是为了处理用户在您的应用中花费大量时间的情况。这种方式在一周之后它最终会被重新启用,但不一定恰好在正确的时间,但通常是正常的。

As a backup , have an NSTimer that fires about once every hour performing the same check , ie calling this function. This is to handle the case where the user spends a lot of time in your app. This way after one week it will be re-enabled eventually , though not necessarily at EXACTLY the right time but that's alright usually.

这篇关于在iOS应用中安排任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆