0

我的应用程序中有一个电池电量指示器,我希望它还在电池电量指示器页面上进行更新。目前,如果我让我的应用程序在该屏幕上保持打开状态并且电池电量发生变化(超过 5%),应用程序就会崩溃。我需要在我的代码中添加什么来做到这一点?这是我的代码:

- (void)viewDidLoad {
[super viewDidLoad];

deviceType.text = [[UIDevice currentDevice] model];

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
[[UIDevice currentDevice] batteryLevel];

// Enable monitoring of battery status
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

// Request to be notified when battery charge or state changes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
}

- (void) viewWillAppear:(BOOL)animated {
UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;
LabelBatteryStatus.text = [NSString stringWithFormat:@"%.0f%%", device.batteryLevel * 100];
[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"]) {
    LabelBatteryStatus.text = [NSString stringWithFormat:@"%.0f%%", device.batteryLevel * 100];
}
}

当我加载和卸载页面时,此代码适用于我的应用程序,但我希望它在页面上时也能正常工作。

提前谢谢你。

4

0 回答 0