------------------------- | Device Info Access | |-----------------------| | Device Name: | | [Loading...] | | | | Battery Level: | | [Loading...] | | | | [Refresh Info] Button | -------------------------
Why platform APIs access device capabilities in iOS Swift - Build It to Prove It
import SwiftUI struct DeviceInfoView: View { @State private var deviceName: String = "Loading..." @State private var batteryLevel: String = "Loading..." 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") { // TODO: Add code to update device info } .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) Spacer() } .padding() // TODO: Add code to fetch info when view appears } } struct DeviceInfoView_Previews: PreviewProvider { static var previews: some View { DeviceInfoView() } }
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.
------------------------- | Device Info Access | |-----------------------| | Device Name: | | John's iPhone | | | | Battery Level: | | 87% | | | | [Refresh Info] Button | -------------------------
Practice
Solution
Step 1: Understand platform API role
Platform APIs act as a safe bridge between apps and device hardware.Step 2: Recognize privacy and security purpose
They manage permissions to protect user data and privacy when apps access features like camera or GPS.Final Answer:
To let apps use device features safely and protect user privacy -> Option AQuick Check:
Platform APIs = safe device access [OK]
- Thinking APIs slow down the device
- Believing APIs allow apps to change system settings freely
- Confusing background app behavior with device access
Solution
Step 1: Identify correct API method
The official method to request camera access is AVCaptureDevice.requestAccess(for: .video).Step 2: Check method syntax
It takes a closure to handle the user's response, matching the code in AVCaptureDevice.requestAccess(for: .video) { granted in /* handle */ }.Final Answer:
AVCaptureDevice.requestAccess(for: .video) { granted in /* handle */ } -> Option CQuick Check:
Correct API method = AVCaptureDevice.requestAccess(for: .video) { granted in /* handle */ } [OK]
- Using non-existent methods like requestPermission()
- Omitting the closure parameter
- Confusing method names with similar sounding ones
CLLocationManager().requestWhenInUseAuthorization()
print("Permission status: \(CLLocationManager.authorizationStatus())")Solution
Step 1: Understand authorizationStatus meaning
authorizationStatus() returns the current permission state for location access.Step 2: Analyze execution timing
requestWhenInUseAuthorization() is asynchronous; the print executes immediately before user response, so status is .notDetermined even if denied later.Final Answer:
Permission status: notDetermined -> Option BQuick Check:
Immediate status after async request = notDetermined [OK]
- Confusing notDetermined with denied
- Assuming authorizedWhenInUse prints without user approval
- Mixing restricted with denied
let audioSession = AVAudioSession.sharedInstance() try audioSession.setActive(true) // Missing permission request let recorder = AVAudioRecorder(url: URL(fileURLWithPath: NSTemporaryDirectory() + "temp.m4a"), settings: nil) recorder.record()
Solution
Step 1: Check permission handling
The code does not request microphone permission, which is required before recording.Step 2: Confirm other code parts
AVAudioSession.sharedInstance() is correct, AVAudioRecorder is initialized with required URL and settings parameters, and record() exists.Final Answer:
Missing call to request microphone permission before recording -> Option DQuick Check:
Permission request missing = Missing call to request microphone permission before recording [OK]
- Thinking AVAudioSession.sharedInstance() is wrong
- Ignoring the need for permission requests
- Assuming AVAudioRecorder() can be used without initialization
Solution
Step 1: Understand permission best practices
Requesting permissions separately lets users control access and improves privacy.Step 2: Recognize importance of handling denial
Handling denial gracefully avoids app crashes and respects user choice.Step 3: Evaluate other options
Direct access without permission is not allowed; assuming permissions or requesting all at install violates privacy rules.Final Answer:
Request camera and location permissions separately using platform APIs and handle denial gracefully -> Option AQuick Check:
Separate permission requests + graceful handling = Request camera and location permissions separately using platform APIs and handle denial gracefully [OK]
- Trying to access features without permission
- Assuming permissions are granted by default
- Requesting all permissions upfront without explanation
Ready to prove it?
Pass the test and this pattern moves unknown
