2014-09-04 69 views
1

即使我的iPhone電池100%充電,我得到的電池狀態爲UIDeviceBatteryStateCharging目前的電池狀態總是返回「充電」在ios

它應該給我狀態爲UIDeviceBatteryStateFull

我的代碼如下。

[[UIDevice currentDevice]setBatteryMonitoringEnabled:YES]; 
    int i=[[UIDevice currentDevice] batteryState]; 
    switch (i) 
    { 
     case UIDeviceBatteryStateUnplugged: 
     { 
      NSLog(@"UnpluggedKey"); 

      break; 
     } 
     case UIDeviceBatteryStateFull: 
     { 
      NSLog(@"FullKey"); 

      break; 
     } 
     case UIDeviceBatteryStateCharging: 
     { 
      NSLog(@"ChargingKey"); 
      break; 
     } 
     default: 
     { 
      NSLog(@"UnknownKey"); 
      break; 
     } 
    } 

    NSLog(@"Battery Status is :%d",i); 
+0

檢查我的答案 – karthikeyan 2014-09-04 13:51:54

回答

2

可以幫你試試這個.....

- (void)viewDidLoad 
{ 
// Enable monitoring of battery status 
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 

    // Print current status 
    [self batteryStatus]; 

    // Request to be notified when battery charge or state changes 
    [[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) 
    { 
     NSLog(@"%@", [batteryStatus objectAtIndex:0]); 
    } 
    else 
    {  
    NSString *msg = [NSString stringWithFormat: 
             @"Battery charge level: %0.2f%%\n%@", [[UIDevice currentDevice] batteryLevel] * 100, 
         [batteryStatus objectAtIndex:[[UIDevice currentDevice] batteryState]] ]; 
     NSLog(@"%@", msg); 
    } 
} 

,你的答案是...

您正在使用不同的枚舉密鑰值檢查

typedef NS_ENUM(NSInteger, UIDeviceBatteryState) { 
    UIDeviceBatteryStateUnknown, 
    UIDeviceBatteryStateUnplugged, // on battery, discharging 
    UIDeviceBatteryStateCharging, // plugged in, less than 100% 
    UIDeviceBatteryStateFull,  // plugged in, at 100% 
};    // available in iPhone 3.0 

更改您的代碼,就像這樣它會工作

[[UIDevice currentDevice]setBatteryMonitoringEnabled:YES]; 
    int i=[[UIDevice currentDevice] batteryState]; 
    switch (i) 
    { 
     case UIDeviceBatteryStateUnplugged: 
     { 
      NSLog(@"UnpluggedKey"); 

      break; 
     } 
     case UIDeviceBatteryStateCharging: 
     { 
      NSLog(@"ChargingKey"); 
      break; 
     } 
     case UIDeviceBatteryStateFull: 
     { 
      NSLog(@"FullKey"); 

      break; 
     } 

     default: 
     { 
      NSLog(@"UnknownKey"); 
      break; 
     } 
    } 

    NSLog(@"Battery Status is :%d",i); 

我希望它會幫助你