如何在xcode iphone中集成倒计时和闹钟?请提供源代码

Moh*_*hit 0 iphone

如何在xcode iphone中集成倒计时和闹钟?请提供源代码.....我已经尝试了很多...但没有找到任何具体的解决方案...请帮帮我...

Bre*_*rse 5

倒计时不是很难整合,只需使用NSTimer:

NSTimer *countdown = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerTicked:) userInfo:nil repeats:YES]; 
Run Code Online (Sandbox Code Playgroud)

只需将计时器倒数到您想要的秒数:

- (void)timerTicked:(NSTimer *)countdown{
    seconds--; // Some pre-declared variable

    // UI Updates Here if you want

    if (seconds <= 0)
        [countdown invalidate]; 
}
Run Code Online (Sandbox Code Playgroud)

警报会有点复杂,但仍然不会太难.根据您设置闹钟的方式,有几种方法可以做到这一点.如果它很快就会使用一个计时器:

NSTimer *alarm = [NSTimer timerWithTimeInterval:SECONDS target:self selector:@selector(alarmDoneMethod) userInfo:nil repeats:NO];
Run Code Online (Sandbox Code Playgroud)

但是我假设你想让它能够在未来几小时或几天设置.在这种情况下使用NSDate.

NSDateComponents *alarmComponents = [[NSDateComponents alloc] init]; 
[alarmComponents setMinute:userInputMinute];
[alarmComponents setHour:userInputHour]; 
[alarmComponents setDay:userInputDay];
[alarmComponents setMonth:userInputMonth];
[alarmComponents setYear:userInputYear];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDate *alarm = [gregorian dateFromComponents:alarmComponents];
[alarmComponents release]; 
Run Code Online (Sandbox Code Playgroud)

现在只需设置一个计时器(我确定有一种更有效的方法可以做到这一点,但我现在无法想到这一点,现在还是在当天早些时候)来检查你的警报是否有到达了:

NSTimer *checkAlarm = [NSTimer timerWithTimeInterval:60.0 target:self selector:@selector(checkAlarm:) userInfo:nil repeats:YES]; // Checks every minute
Run Code Online (Sandbox Code Playgroud)

然后在checkAlarm:方法内部查看是否已达到警报:

-(void)checkAlarm:(NSTimer *)t{
    if ([[NSDate date] earlierDate:alarm] == alarm){
        // Alarm reached
        [t invalidate]; 
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

干杯.