在iOS应用程序中安排任务

时间:2015-08-27 11:30:29

标签: ios

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

2 个答案:

答案 0 :(得分:6)

我建议使用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 :(得分:1)

<强> 1。方法 我建议使用NSTimer Class并设置一个计时器来调用将取消静音的功能。还有在后台使用方法的后台任务,可以通过添加

来完成
.directive('uiSubmitButton', function() {

    return {
      restrict: 'E',
      template : function() {
        return ' \
          <button class="btn btn-success" type="submit" ng-disabled="btnState"> \
            <input type="checkbox" ng-model="btnState" /> {{btnState}} \
            <i class="fa fa-cog" ng-show="btnState" /> \
            <span ng-hide="btnState">{{btnLabel || "Submit"}}</span> \
          </button>';
      },
      replace : true,
      scope : {
        btnState : '=',
        btnLabel : '@'
      }
    };

  })

在致电时间表之前。

例如,我想静音8小时,而不是你需要打电话

var bgTask = UIBackgroundTaskIdentifier
var app = UIApplication.sharedApplication()
app.beginBackgroundTaskWithExpirationHandler { () -> Void in
    app.endBackgroundTask(bgTask)
}

并添加您的NSTimer.scheduledTimerWithTimeInterval(60*8, target:(self), selector: Selector("stopper"), userInfo: nil, repeats: no);

stopper

您也可以通过向计时器添加func stopper(){ //unmute } 来发送有关将被静音的对象的特定信息。

<强> 2。方法

您可以查看userInfoapplicationDidEnterBackground

之间的时差

applicationDidEnterForeground和差异let date = NSDate.date()

相关问题