Swift 備忘録 「バッテリーに関する情報の取得方法」

忘れそうなのでメモ

        var batteryStatusName: String;        

        let device = UIDevice.currentDevice();
        
        //これしないと全部Unknown返る
        device.batteryMonitoringEnabled = true;
        
        var batteryLevel = device.batteryLevel;
        
        switch device.batteryState{
        case .Full:
            //満充電
            batteryStatusName = "FULL";
            break;

        case .Charging:
            //充電中
            batteryStatusName = "Charging";
            break;
            
        case .Unplugged:
            //未接続
            batteryStatusName = "Unplugged";
            break;

        case .Unknown:
            //不明
            batteryStatusName = "Unknown";
            break;
            
        default:
            batteryStatusName = "";
            break;
            
        }

        //BatteryLevelは 0.0〜1.0で返る。Unknownの時は-1.0

        println("Battery \(batteryLevel) \(batteryStatusText)");

About the author