iOSに歩数計を実装しています。重要な要件は、アプリがバックグラウンド モードになった場合でも機能する必要があることです (たとえば、デバイスがロックされているか、ユーザーがホーム ボタンを押した場合)。このような実装は、Nike+、Runtastic Pedometer などの App Store で見ることができます。
いくつかの SO 投稿で、これが Core Motion で、または具体的にはset toCMMotionManager
の追加プロパティで可能になることが確認されました。Required background modes
location
以下のコードで簡単なテストを実行したところ、奇妙な問題が見つかりました。
// AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application
{
if(self.motionManager==nil) {
self.motionManager=[[CMMotionManager alloc] init];
}
self.motionManager.accelerometerUpdateInterval=1/50;
if(self.accelerometerReadings==nil)
self.accelerometerReadings=[[NSMutableArray alloc] init];
[self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.accelerometerReadings addObject:accelerometerData];
});
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
NSLog(@"The number of readings %d",self.accelerometerReadings.count);
// do something with accelerometer data...
}
このコードを iPhone 4S と iOS 6.1 で試しました。アプリが起動したら、ホーム ボタンを押して (歩行をシミュレートするために) 5 秒間振ってから、もう一度アプリを開きます。これらのアクションは数回繰り返されます。私が得た出力は次のとおりです。
2013-02-05 16:41:42.028 [1147:907] readings 0
2013-02-05 16:41:51.572 [1147:907] readings 444
2013-02-05 16:42:00.386 [1147:907] readings 1032
2013-02-05 16:42:08.026 [1147:907] readings 1555
...
読み取り値の正確性は確認していませんが、簡単に観察すると、すでにいくつかの問題が明らかになりました。このアプリがバックグラウンド モードで初めて実行されたときは、読み取り値はありません (または 1 つだけの場合もあります)。
ここで何が間違っていますか?そして、これは歩数計を実装するための正しいアプローチですか?