Use iPhone's Proximity Sensor

Hi ✋ I'm trying to build an app with SwiftUI, and I'm completely new to coding. I want to use iPhone's proximity sensor as a feature in my app.

This is not what I actually want, but to make it simple:

Say there is a number shown on the screen. Whenever I cover the iPhone's proximity sensor with my hand, the number is increased by one. theNumber += 1

import SwiftUI

struct ContentView: View {
    @State private var theNumber: Int = 0

    var body: some View {
        Text("\(theNumber)")
    }
}
Accepted Answer

You can retrieve the proximityState value from the current UIDevice and detect when it changes. You need to enable proximity monitoring first and I suggest doing that in your main App struct.

// in main App struct
init() {
    UIDevice.current.isProximityMonitoringEnabled = true
}
struct ContentView: View {
    @State private var theNumber = 0

    var body: some View {
        Text("\(theNumber)")
            .onReceive(NotificationCenter.default.publisher(for: UIDevice.proximityStateDidChangeNotification)) { _ in
                if UIDevice.current.proximityState {
                    // sensor is close to user
                    // true is "near", false is "far"

                    theNumber += 1
                }
            }
    }
}



Things to Note

  • The sensor detects objects up to 10 cm away.
  • When the sensor detects an object that is close, the screen turns off.
  • There is no single point where the proximity state switches between "near" and "far", but instead a buffer range.
  • When the state is "far", the object must be up to 5 cm from the sensor in order to change the state to "near".
  • When the state is "near", the object must be at least 10 cm from the sensor in order to change the state to "far".

Thanks for this

I copied this code and ran it on my iPhone 13. The number does not change. I did confirm that my sensor was working by calling someone to see if my screen turns off.

Use iPhone's Proximity Sensor
 
 
Q