8
を決定し、私は次のようにバッテリーレベル/状態を取得しようとしている:は、正確なiPhoneのバッテリーレベル
- (void) viewWillAppear: (BOOL) animated{
[self viewWillAppear:animated];
// Battery state
[self batteryStatus];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryStateDidChangeNotification object:nil];
}
- (void)batteryStatus
{
NSArray *batteryStatus = [NSArray arrayWithObjects:
@"Battery status is unknown.",
@"Battery is in use (discharging).",
@"Battery is charging.",
@"Battery is fully charged.", nil];
if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateUnknown)
{
[textViewStatus setText:[batteryStatus objectAtIndex:0]];
NSLog(@"%@", [batteryStatus objectAtIndex:0]);
}
else
{
NSString *msg = [NSString stringWithFormat:@"Battery charge level: %0.2f%%\n%@", [[UIDevice currentDevice] batteryLevel] * 100,[batteryStatus objectAtIndex:[[UIDevice currentDevice] batteryState]] ];
[textViewStatus setText:msg];
NSLog(@"%@", msg);
}
}
しかし、私はバッテリーレベルの変更を取得していないですし、値が正確ではありません。
- (void) viewWillAppear:(BOOL)animated {
UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;
textViewStatus.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];
[device addObserver:self forKeyPath:@"batteryLevel" options:0x0 context:nil];
[super viewWillAppear:animated];
}
- (void) viewDidDisappear:(BOOL)animated {
UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = NO;
[device removeObserver:self forKeyPath:@"batteryLevel"];
[super viewDidDisappear:animated];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UIDevice *device = [UIDevice currentDevice];
if ([object isEqual:device] && [keyPath isEqual:@"batteryLevel"]) {
NSLog(@"Battery level :%f",device.batteryLevel);
textViewStatus.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];
}
}
私はあなたのコードと特異的に間違って何も見えないことができますが
ありがとうございます。はい、その変化を5%間隔で示します。しかし、私はあらゆるレベルで変化を示したいと思っています。 –
@sandhyaこれは、SDKとAppleが技術的に設計した方法の制限です。アップルのドキュメントによると... 'バッテリーレベルの変更の通知は、1分に1回以上送信されません。 ' –
アプリが終了すると、これらの通知を使用できますか?なぜあなたに尋ねるのか分からない – Apple