2011-06-27 686 views
8

Estoy tratando de obtener el nivel de batería/Estado de la siguiente manera:determinar el nivel de la batería iPhone precisa

- (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); 
    } 
} 

Sin embargo, no estoy recibiendo los cambios en el nivel de la batería, y los valores no son exactos.

- (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]; 
    } 
} 

¿Alguna idea?

Respuesta

21

Aunque no puedo ver nada específicamente mal con su código, intenta lo siguiente

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    UIDevice *device = [UIDevice currentDevice]; 
    device.batteryMonitoringEnabled = YES; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:device]; 
} 

- (void)batteryChanged:(NSNotification *)notification 
{ 
    UIDevice *device = [UIDevice currentDevice]; 
    NSLog(@"State: %i Charge: %f", device.batteryState, device.batteryLevel); 
} 

Además, vale la pena señalar que en mi experiencia las notificaciones sólo alguna vez el fuego a intervalos de 5%, es decir cuando la batería los cambios de nivel de 100% a 95% y 95% a 90% etc.

+0

Gracias por su respuesta. Sí, muestra los cambios a intervalos de 5%. Pero quiero mostrar los cambios en todos los niveles. –

+0

@sandhya Esta es una limitación del SDK y la forma en que Apple eligió diseñarlo. Según los documentos de Apple ... 'Las notificaciones para el cambio del nivel de batería se envían con una frecuencia no mayor a –

+0

cuando la aplicación está cerrada, ¿podemos utilizar estas notificaciones? No estoy seguro de por qué preguntarle .. – Apple

Cuestiones relacionadas