Home Swift UNIX C Assembly Go Web MCU Research Non-Tech

How to obtain information of device, system and battery in Swift.

2021-04-03 | Swift | #Words: 420 | 中文原版

UIDevice is an API for obtaining device information. We need add .current to get current device information. Such as:

let name = UIDevice.current.name

It will display the device name (“General-About This xxx-Name”), such as “xxx’s iPhone”.

It has some other properties:

For battery, it can display the status or level.

First turn on isBatteryMonitoringEnabled use the following (Here is two types:

var batteryLevel: Int {
    UIDevice.current.isBatteryMonitoringEnabled = true
    let data = Int(UIDevice.current.batteryLevel * 100)
 
    return data
}

// Function
func battery() -> Int {
    // Enable isBatteryMonitoringEnabled
    UIDevice.current.isBatteryMonitoringEnabled = true
 
    // Obtain battery level (in Float, the range is 0-1, here multiplied by 100 and converted into integer form)
    let batterylevel = Int(UIDevice.current.batteryLevel * 100)
    
    // Return level
    return batterylevel
}

// Closure
let battery = { () -> Int in
    // Enable isBatteryMonitoringEnabled
    UIDevice.current.isBatteryMonitoringEnabled = true
 
    // Obtain battery level (in Float, the range is 0-1, here multiplied by 100 and converted into integer form)
    let batterylevel = Int(UIDevice.current.batteryLevel * 100)
    
    // Return level
    return batterylevel
}

And we can use the returned value:

struct ContentView: View {
    var body: some View {
        VStack{
            Text("\(battery())")
                .padding()
        }
    }
}

Now we can see the battery level.

I hope these will help someone in need~