Objective-C (iOS): バッテリーの状態監視

実機で確認してください。

Objective-C: BatteryStateCheckViewController.h

#import <UIKit/UIKit.h>

@interface BatteryStateCheckViewController : UIViewController
{
    NSNumberFormatter *numberFormatter;
}

@end

Objective-C: BatteryStateCheckViewController.m

#import "BatteryStateCheckViewController.h"

@implementation BatteryStateCheckViewController

- (void)viewDidLoad
{
    [UIDevice currentDevice].batteryMonitoringEnabled = YES;
    float batteryLevel = [UIDevice currentDevice].batteryLevel;
    NSNumber *levelObj = [NSNumber numberWithFloat:batteryLevel];
    NSString *batteryPercent = [self.numberFormatter stringFromNumber:levelObj];
    NSLog(@"%@", batteryPercent);
    UIDeviceBatteryState batteryState = [UIDevice currentDevice].batteryState;
    NSLog(@"%d", batteryState);
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(batteryLevelDidChange:)
                                                 name:UIDeviceBatteryLevelDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(batteryStateDidChange:)
                                                 name:UIDeviceBatteryStateDidChangeNotification object:nil];
    
}
- (NSNumberFormatter *)numberFormatter
{
    if (numberFormatter == nil)
    {
        numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];
        [numberFormatter setMaximumFractionDigits:1];
    }
    return numberFormatter;
}

#pragma mark - Battery notifications

- (void)batteryLevelDidChange:(NSNotification *)notification
{
    float batteryLevel = [UIDevice currentDevice].batteryLevel;
    NSNumber *levelObj = [NSNumber numberWithFloat:batteryLevel];
    NSString *batteryPercent = [self.numberFormatter stringFromNumber:levelObj];
    NSLog(@"%@", batteryPercent);
}


- (void)batteryStateDidChange:(NSNotification *)notification
{
    UIDeviceBatteryState batteryState = [UIDevice currentDevice].batteryState;
    NSLog(@"%d", batteryState);
}
@end