import SwiftUI
import UIKit
struct DeviceInfoView: View {
@State private var deviceName: String = "Loading..."
@State private var batteryLevel: String = "Loading..."
func updateDeviceInfo() {
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
deviceName = device.name
let level = device.batteryLevel
if level < 0 {
batteryLevel = "Unknown"
} else {
batteryLevel = String(format: "%.0f%%", level * 100)
}
}
var body: some View {
VStack(spacing: 20) {
Text("Device Info Access")
.font(.title)
.padding()
VStack(alignment: .leading, spacing: 10) {
Text("Device Name:")
Text(deviceName)
.fontWeight(.bold)
Text("Battery Level:")
Text(batteryLevel)
.fontWeight(.bold)
}
Button("Refresh Info") {
updateDeviceInfo()
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
Spacer()
}
.padding()
.onAppear {
updateDeviceInfo()
}
}
}
struct DeviceInfoView_Previews: PreviewProvider {
static var previews: some View {
DeviceInfoView()
}
}This app screen uses platform APIs from UIDevice to access device capabilities.
We get the device name from UIDevice.current.name. This tells us the name the user gave their device, like "John's iPhone".
We also get the battery level from UIDevice.current.batteryLevel. We enable battery monitoring first to get this info. The battery level is a float from 0.0 to 1.0, so we convert it to a percentage string.
The "Refresh Info" button calls the updateDeviceInfo() function to fetch and show the latest info. We also call this function when the view appears so the info loads right away.
This shows how platform APIs let apps safely and easily access device features like name and battery status.