iOS倒计时,应用程序徽章编号,并节省剩余时间

时间:2016-02-19 16:12:52

标签: ios objective-c

我需要一些帮助,希望在剩下的几天内创建一个图标徽章编号 我需要帮助来节省你关闭应用程序时剩下的时间,所以它一直在计算。

我尝试在网上寻找,但我还不足以了解所有代码的位置。

如果我留在应用程序中,倒计时工作正常。

.h文件

@interface ViewController : UIViewController

   @property (weak, nonatomic) IBOutlet UIButton *startCountdown;
   @property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
   @property (weak, nonatomic) IBOutlet UILabel *countdownLabel;
   - (IBAction)startCountdown:(id)sender;

@end

.m文件

- (IBAction)startCountdown:(id)sender {
    //Remove the time component from the datePicker.  We care only about the date
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    NSUInteger preservedComponents = (NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay);
    self.datePicker.date = [calendar dateFromComponents:[calendar components:preservedComponents fromDate:self.datePicker.date]];

    //Set up a timer that calls the updateTime method every second to update the label
    NSTimer *timer;
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                             target:self
                                           selector:@selector(updateTime)
                                           userInfo:nil
                                            repeats:YES];
}

-(void)updateTime
{
    //Get the time left until the specified date
    NSInteger ti = ((NSInteger)[self.datePicker.date timeIntervalSinceNow]);
    NSInteger seconds = ti % 60;
    NSInteger minutes = (ti / 60) % 60;
    NSInteger hours = (ti / 3600) % 24;
    NSInteger days = (ti / 86400);

    //Update the label with the remaining time
    self.countdownLabel.text = [NSString stringWithFormat:@"%02li days %02li hrs %02li min %02li sec", (long)days, (long)hours, (long)minutes, (long)seconds];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

1 个答案:

答案 0 :(得分:0)

我想知道你在哪里保存datePicker的价值。当我阅读您在此问题中提供的代码时,关闭应用程序后将丢弃所有值。在应用程序的某个位置,您应该保留更新的剩余时间。当我阅读你的代码时,你会启动一个计时器来衡量datePickers的时间与计时器启动之间的时差。

您可以构建一个包含剩余时间的类,并使该类符合NSCoding协议。然后实现encodeWithCoder:(NSCoder *)编码器方法,用于保存剩余的时间类并实现initWithCoder:(NSCoder *)解码器以加载剩余时间。

在视图控制器中,例如,在viewDidLoad [NSKEyedUnarchiver unarchiveObjectWithFile:(NSString *)path]中调用以加载保存剩余时间。当应用程序关闭时,您调用[NSKeyedArchiver archiveRootObject:yourTimer toFile:path]

然后你的计时器将恢复计数。