0

それらがそうであるかどうかは完全に理解していますが、私が探しているのは、アプリケーションがバックグラウンドに入ると一時停止し、ユーザーがアプリに戻った後に一時停止を解除するタイマーです。バックグラウンド タスクは必要ありません。アプリ内で約 x 分後に、今日か明日かにかかわらず、特定のアクションが発生することを確認したいだけです。

ありがとう!ブレット

4

1 に答える 1

1

アプリをバックグラウンド化しても (バックグラウンド タスクがない場合)、タイマーは「一時停止」しません。理論上はまだカウントダウン中なので、アプリを再度開いた場合、十分な時間が経過すると起動します。これは NSTimer にも当てはまります。(理由の詳細が必要な場合はお知らせください。回答を編集します)。

次のコードの使用を検討してください。

@implementation MyCustomClass {
    int elapsedTime;
    NSTimer *timer;
}

- (id) init {
    if ( ( self = [super init] ) ) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(applicationEnteredBackground)
                                                     name:UIApplicationDidEnterBackgroundNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(applicationEnteredForeground)
                                                     name:UIApplicationDidBecomeActiveNotification
                                                   object:nil];
    }
    return self;
}


- (void) applicationEnteredForeground { 
    timer = [NSTimer timerWithTimeInterval:1
                                    target:self
                                  selector:@selector(timerTicked)
                                  userInfo:nil
                                   repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void) applicationEnteredBackground {
    [timer invalidate];
}

- (void) timerTicked {
    elapsedTime += 1;
    // If enough time passed, do something
}
于 2013-05-24T01:33:36.710 に答える