バックグラウンド動作中のアプリから前面にアラートを送ってみたのこと
iOS4のマルチタスキングねた第二弾。
(第一弾はこちら: http://d.hatena.ne.jp/epocha/20100608/1276022504)
前回作成した、
(ラーメ…マー)
ことラーメンタイマーが全然タイマーにならないので、
バックグラウンドで動作中、3分たったときに前面にアラートを出してみることにしました。
というわけで、カウントアップのメソッドをいじります。
前回のコード
- (void)countUp { count++; [timerLabel setText:[NSString stringWithFormat:@"%d", count]]; [self performSelector:@selector(countUp) withObject:nil afterDelay:1.0]; }
今回のコード
- (void)countUp { count++; if(count == 180) { UILocalNotification *localNotif = [[UILocalNotification alloc] init]; if (localNotif) { localNotif.alertBody = @"ラーメンできたよ!"; localNotif.alertAction = @"食べない"; localNotif.soundName = @"alarmsound.caf"; [[UIApplication sharedApplication] presentLocalNotificationNow:localNotif]; [localNotif release]; } } [timerLabel setText:[NSString stringWithFormat:@"%d", count]]; [self performSelector:@selector(countUp) withObject:nil afterDelay:1.0]; }
かなり適当な実装ですが、テストなので良しとします。
やっていることは、
- UILocalNotificationのインスタンスを作成
- alertBody, alertAction, soundNameを指定
- アプリのUIApplicationインスタンス([UIApplication sharedApplication]で取得)にpresentLocalNotificationNowで投げる
以上。
alertActionは「OK」ボタンに相応するボタンの文字列を指定します。
こんな感じで表示されます。
「食べない」と書いてあるボタンを押すと、呼び出し元のアプリが起動されます。
ね、簡単でしょ。
http://twitter.com/epoch__
参考にしたページ:
https://devforums.apple.com/community/iphone/40beta/multitasking
(要デベロッパー登録)