2013-08-20 2 views
0

작업중인 프로젝트에서 일시 중지하고 계속할 스톱워치가 필요합니다. 지금까지 모든 기본 기능이 작동하지만 타이머를 일시 중지하고 다시 시작하는 방법을 찾지 못했습니다. 참고로, 나는 이미 다른 게시물을 확인했으며 작동하지 않았습니다. 코드 :NSTimer/Stopwatch 일시 중지

.H :

#import <UIKit/UIKit.h> 
#import <AVFoundation/AVFoundation.h> 

@interface Timer : UIViewController <AVAudioRecorderDelegate, AVAudioPlayerDelegate> 
{ 
    AVAudioRecorder *recorder; 
    AVAudioPlayer *player; 
} 

@property (weak, nonatomic) IBOutlet UIButton *recordPauseButton; 

@property (weak, nonatomic) IBOutlet UIButton *stopButton; 

@property (weak, nonatomic) IBOutlet UILabel *stopwatchLabel; 


-(IBAction)recordPauseTapped:(id)sender; 

-(IBAction)stopTapped:(id)sender; 

@end 

하는 .m : 귀하의 경우

#import "Timer.h" 

@interface SongIdeasRecording() 

@property (strong, nonatomic) NSTimer *stopWatchTimer; // Store the timer that fires  after a certain time 
@property (strong, nonatomic) NSDate *startDate; // Stores the date of the click on the start button 

@end 


@implementation Timer 

@synthesize stopButton, playButton, recordPauseButton, stopwatchLabel; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
    // Custom initialization 
} 
    return self; 
} 

- (void)updateTimer 
{ 
    // Timer is 1/10 of a second so thats what we add to stopwatch 
NSTimeInterval timeInterval = 0.1; 

// Create a date formatter 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 

// Take the time currently displayed on the stopwatch and add the time interval to it 
NSDate *oldDate = [dateFormatter dateFromString:self.stopwatchLabel.text]; 
NSDate *newDate = [oldDate dateByAddingTimeInterval:timeInterval]; 
//Get a string representation of the new date 
NSString *timeString = [dateFormatter stringFromDate:newDate]; 
self.stopwatchLabel.text = timeString; 
} 

- (IBAction)recordPauseTapped:(id)sender { 
    self.startDate = [NSDate date]; 

    // Create the stop watch timer that fires every 100 ms 
    self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 
                 target:self 
                selector:@selector(updateTimer) 
                userInfo:nil 
                 repeats:YES]; 



    // Stop the audio player before recording 
    if (player.playing) { 
     [player stop]; 
    } 

    if (!recorder.recording) { 
    AVAudioSession *session = [AVAudioSession sharedInstance]; 
    [session setActive:YES error:nil]; 

    // Start recording 
    [recorder record]; 
    [recordPauseButton setTitle:@"Pause" forState:UIControlStateNormal]; 

    } else { 

     // Pause recording 
     [self.stopWatchTimer invalidate]; 
     self.stopWatchTimer = nil; 
     [self updateTimer]; 
     [recorder pause]; 
     [recordPauseButton setTitle:@"Record" forState:UIControlStateNormal]; 

    } 

     [stopButton setEnabled:YES]; 
     [playButton setEnabled:NO]; 
} 
- (IBAction)stopTapped:(id)sender { 
    [recorder stop]; 

    AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 
    [audioSession setActive:NO error:nil]; 

    [self.stopWatchTimer invalidate]; 
    self.stopWatchTimer = nil; 
    [self updateTimer]; 
} 

- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully: (BOOL)flag{ 
    [recordPauseButton setTitle:@"Record" forState:UIControlStateNormal]; 

    [stopButton setEnabled:NO]; 
    [playButton setEnabled:YES]; 
} 

- (IBAction)playTapped:(id)sender { 
    if (!recorder.recording){ 
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil]; 
    [player setDelegate:self]; 
    [player play]; 
    self.startDate = [NSDate date]; 
    stopwatchLabel.text = @"00:00:00.000"; 
    self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 
                  target:self 
                 selector:@selector(updateTimer) 
                 userInfo:nil 
                  repeats:YES]; 

    } 
    } 

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag 
{ 
    [self.stopWatchTimer invalidate]; 
    self.stopWatchTimer = nil; 
    [self updateTimer]; 
    } 


@end 
+2

"관련"섹션에 표시된 몇 가지 결과가 특히 잘못되었습니다. "그들이 효과가 없다"고 말하면서도 안됩니다. 아니면 귀하의 질문을 복제물로 표시 할 것입니다. – borrrden

답변

0

, 당신은 녹화 버튼 원래 누른 것을 NSDate와 스톱워치 레이블의 값을 계산한다. 스톱워치 레이블 값을 다시 계산할 때마다 기록 단추가 눌린 원래 날짜가 반영되므로 타이머를 일시 중지 할 방법이 없습니다. 이 방법을 다음과 같이 변경하는 것이 좋습니다.

- (void)updateTimer 
{ 
    // Timer is 1/10 of a second so thats what we add to stopwatch 
    NSTimeInterval timeInterval = 0.1; 

    // Create a date formatter 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"HH:mm:ss.SSS"]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 

    // Take the time currently displayed on the stopwatch and add the time interval to it 
    NSDate *oldDate = [dateFormatter dateFromString:self.stopwatchLabel.text]; 
    NSDate *newDate = [oldDate dateByAddingTimeInterval:timeInterval]; 
    //Get a string representation of the new date and BOOM POW. 
    NSString *timeString = [dateFormatter stringFromDate:newDate]; 
    self.stopwatchLabel.text = timeString; 
} 

테스트하지 않았지만 제대로 작동하는지 확인하십시오. 문법상의 문제가 있다면 놀라지 않을 것입니다. 또한 self.stopwatchLabel.text에있는 문자열이 시작할 형식 (예 : 00 : 00 : 00.000)을 따르는 지 확인하십시오.

+0

지금 타이머를 일시 중지하려면 클릭해도 계속 실행됩니다. 이제는 이전처럼 타이머를 시작하지 않습니다. 내가 넣어 [self.stopWatchTimer 무효]; self.stopWatchTimer = nil; [self updateTimer]; 일시 정지 기록 주석 아래에 있습니다. –

+0

타이머가 여러 개있을 수 있습니까? 타이머를 무효화하면 타이머가 중지됩니다. 그런 다음 다시 시작하려면 새 타이머를 만들어야합니다. –

+0

어디에서 스톱워치를 재개합니까? –

0

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player 내부 코드에 주석을 달아보십시오.

제 생각 엔 - (IBAction)recordPauseTapped:(id)sender[player stop]이 호출되어 새 타이머를 무효로하는 - (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag이 발생합니다.

0
- (IBAction)recordPauseTapped:(id)sender { 

    if ([stopwatchLabel.text isEqual: @"00:00:00.000"]) { 


    self.startDate = [NSDate date]; 

    // Create the stop watch timer that fires every 100 ms 
    self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 
                 target:self 
                selector:@selector(updateTimer) 
                userInfo:nil 
                 repeats:YES]; 



    // Stop the audio player before recording 
    if (player.playing) { 
    [player stop]; 
    } 

if (!recorder.recording) { 
    AVAudioSession *session = [AVAudioSession sharedInstance]; 
    [session setActive:YES error:nil]; 

    // Start recording 
    [recorder record]; 
    [recordPauseButton setTitle:@"Pause" forState:UIControlStateNormal]; 

} 
}else { 

    // Pause recording 
    [self.stopWatchTimer invalidate]; 
    self.stopWatchTimer = nil; 
    [self updateTimer]; 
    [recorder pause]; 
    [recordPauseButton setTitle:@"Record" forState:UIControlStateNormal]; 

} 

[stopButton setEnabled:YES]; 
[playButton setEnabled:NO]; 


} 
관련 문제