iphone - 如何让我的计时器在后台运行,然后发送本地通知?

标签 iphone ios objective-c nstimer uilocalnotification

出于某种原因,我的计时器只在前台运行。我在这里搜索了解决方案,但找不到任何好的解决方案。我的计时器使用核心数据,每次递减后都会保存我的 timeInterval。另外,我正在发送 UILocalNotification 但这不起作用。我假设如果它在前台它不会发送警报 View ..这就是我现在所拥有的:

-(IBAction)startTimer:(id)sender{
    if (timer == nil) {
        [startButton setTitle:@"Pause" forState:UIControlStateNormal];
       timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    } else {
        [startButton setTitle:@"Resume" forState:UIControlStateNormal];
        [timer invalidate];
        timer = nil;
    }

}
-(void)timerAction:(NSTimer *)t
{
    if(testTask.timeInterval == 0)
    {
        if (self.timer)
        {
            [self timerExpired];
            [self.timer invalidate];
            self.timer = nil;
        }
    }
    else
    {
        testTask.timeInterval--;
        NSError *error;
        if (![self.context save:&error]) {
            NSLog(@"couldn't save: %@", [error localizedDescription]);
        }
    }
    NSUInteger seconds = (NSUInteger)round(testTask.timeInterval);
    NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
                        seconds / 3600, (seconds / 60) % 60, seconds % 60];
    timerLabel.text = string;
    NSLog(@"%f", testTask.timeInterval);
}
-(void)timerExpired{
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.alertBody = @"Time is up";
    localNotification.alertAction = @"Ok";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    [[UIApplication sharedApplication]presentLocalNotificationNow:localNotification];
}

我真的很感激一些指导,让我的计时器在后台工作(就像苹果的计时器一样)。我不确定如何使用 NSDateComponents,因为即使应用程序在后台,我也需要更新 testTask.timeInterval ..

最佳答案

UIBackgroundTaskIdentifier bgTask =0;
UIApplication  *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
}];

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
           target:self
           selector:@selector(timerCountDown:)
           userInfo:nil
           repeats:YES];

现在使用此方法触发您的通知。计时器将在后台运行。

关于iphone - 如何让我的计时器在后台运行,然后发送本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18038164/

相关文章:

ios - CSS 未应用于 iOS 设备

iphone - 自动调整蒙版何时在 iOS 中生效?

ios - swift 。设置文本字段中输入的格式

iphone - ScrollView subview 上的旋转手势及其捏缩放可以同时使用吗?

iphone - 我们可以在 Objc 元素上保留没有 getter 和 setter 的属性吗?

iphone - IOS中的P2P编程

ios - 如何在单击删除按钮时更改表行颜色,而不是在 iOS 中删除行

ios - 无法将 dSYM 文件上传到 Fabric Crashlytics

ios - 确定 UIImage 的主要颜色和次要颜色

objective-c - 将图像从iOS上传到Grails