iPhone SDK 3.0 で、特定の時間になるとアプリケーションに警告する通知を登録したいと考えています。出来ますか?ありがとう
5 に答える
NSTimer
セレクターを 30 秒ごとに (または必要な粒度で) 実行する をセットアップします。
[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
セレクター (メソッド)は-timerFired:
30 秒ごとに実行され、時間、分、秒のコンポーネントをチェックし、要素が目的の時間と一致する場合に通知を発行します。
- (void) timerFired:(NSNotification *)notification {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
NSInteger hour = [dateComponents hour];
NSInteger min = [dateComponents minute];
NSInteger sec = [dateComponents second];
if ((hour == kDesiredHour) && (min == kDesiredMinute) && (sec == kDesiredSecond)) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"kTimeComponentsWereMatched" object:nil userInfo:nil];
}
}
この通知をリッスンするために、他のクラスのどこかに登録します。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:@"kTimeComponentsWereMatched" object:nil];
したがって、同じクラスに興味深いことを行うメソッドがあります。
- (void) doSomething:(NSNotification *)notification {
// do something interesting here...
}
すべてが 1 つのクラスにある場合は、このコードをマージできます。または、を実行するクラス インスタンスを指すように を指定target
します。NSTimer
selector
アプリが閉じていても、このタイマーを起動させたいと思います。そのために通知を使用できますが、通知を発行したサーバーが必要になります。
さらに、iPhone はユーザーにアプリを開くように求めるアラートを表示しますが、ユーザーはそうしないことを選択できました。
NSDate
変数に があり、その日付にdate
メソッドを起動したい場合は、次のようにします。dateIsHere:
NSTimer* timer = [[NSTimer alloc] initWithFireDate:date
interval:0.0f
target:self
selector:@selector(dateIsHere:)
userInfo:nil
repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:timer
forMode:NSDefaultRunLoopMode];
[timer release];
バージョン4.0以降iOSに実装されている「ローカル通知」を探しています。
これは、>=4.0の正解です。以前のバージョンでは、おそらくNSNotificationsしかありません(プッシュの実装はほとんどの場合面倒です)
特定の日付に起動するように NSTimer を設定することから始めます。起動するセレクターは、任意のものにすることができます。NSNotifications を使用する必要はありません。