2016-07-26 16 views
1

私はと類似の質問があります:NSTimer run every minute but on first secondNSTimerは、30秒ごとに実行しますが、常にXXの火災:00secまたはXX:分の30秒

を私はタイマーは分の次の第1、第2、または次を開始したいです分の半分。現在の時刻が12min:34secの場合、次の希望の火災時間は13min:00sec、それが12min:15secの場合は12min:30secです。

基本的に私は毎分xx:00secxx:30secを発射する必要があります。

この各第一、第二の発射コードされています。私は分のために右のコンポーネントを見つける必要があり、秒

let currentCalendar = NSCalendar.currentCalendar() 
    let unitFlags: NSCalendarUnit = [.Era, .Year, .Month, .Day, .Hour, .Minute] 
    let components = currentCalendar.components(unitFlags , fromDate: NSDate()) 
    components.minute += 1 
    components.second = 0 

    let nextMinuteDate = currentCalendar.dateFromComponents(components) 

    let reloadTimer = NSTimer.scheduledTimerWithTimeInterval(kReloadDataTimeInterval, target: self, selector: #selector(loadData) , userInfo: nil, repeats: false) 
    reloadTimer.fireDate = nextMinuteDate! 
+1

があなたのコードを貼り付けてい... –

+0

方法(あなたがそのセレクタに渡すものを発射ないのはなぜ)、必要に応じてNSTimerを起動します(毎分30秒または0秒)。 – Larme

+1

問題は何ですか?あなたは何を試してもうまくいかないのですか?あなたのコードはうんざりですか?どのようなエラーメッセージが表示されますか? –

答えて

1
  • var timer : NSTimer! 
    
  • NSTimerプロパティを作成し、プロパティを初期化します非繰り返しタイマを用いた方法と計算時間間隔(30 - (seconds-of-current-date % 30)

    let currentSeconds = NSCalendar.currentCalendar().component(.Second, fromDate: NSDate()) 
    let initialInterval = NSTimeInterval(30 - currentSeconds % 30) 
    timer = NSTimer.scheduledTimerWithTimeInterval(initialInterval, 
                 target: self, 
                 selector: #selector(firstTimerFired(_:)), 
                 userInfo: nil, 
                 repeats: false) 
    
  • selectorを表す方法では、タイマーを30秒の間隔で繰り返し、2番目のセレクターを再初期化します。二つの別個のセレクタを使用

    func firstTimerFired(aTimer : NSTimer) { 
        NSLog("firstTimerFired") 
        timer = NSTimer.scheduledTimerWithTimeInterval(30.0, 
                  target: self, 
                 selector: #selector(timerFired(_:)), 
                 userInfo: nil, 
                  repeats: true) 
    } 
    
  • 最初の実行をチェックする必要if句を回避します。

    func timerFired(aTimer : NSTimer) { 
        NSLog("timerFired") 
    } 
    

NSLog文は(というよりもprint)の印刷は、現在の日付と時刻が日付を証明します。

0

ソリューションanswer of @vadianに触発されたが、二回、スケジュールタイマーにNSTimerを宣言した避け、2つのセレクタ

let currentSeconds = NSCalendar.currentCalendar() 
           .component(.Second, fromDate: NSDate()) 

let initialInterval = NSTimeInterval(30.0 - Double(currentSeconds) % 30.0) 

let fireDate = NSDate().dateByAddingTimeInterval(initialInterval) 

let reloadTimer = NSTimer(fireDate: fireDate, 
           interval: 30.0, 
           target: self, 
           selector: #selector(self.loadData), 
           userInfo: nil, 
           repeats: true) 

NSRunLoop.mainRunLoop().addTimer(reloadTimer, forMode: NSRunLoopCommonModes) 
関連する問題