Skip to content

Instantly share code, notes, and snippets.

@skl
Created May 29, 2020 11:49
Show Gist options
  • Save skl/a093291abc0a90a640e50f78888456e7 to your computer and use it in GitHub Desktop.
Save skl/a093291abc0a90a640e50f78888456e7 to your computer and use it in GitHub Desktop.
iOS SwiftUI proximity observer example
import SwiftUI
import UIKit
class ProximityObserver {
@objc func didChange(notification: NSNotification) {
print("MyView::ProximityObserver.didChange")
if let device = notification.object as? UIDevice {
print(device.proximityState)
}
}
}
struct MyView: View {
var proximityObserver = ProximityObserver()
func activateProximitySensor() {
print("MyView::activateProximitySensor")
UIDevice.current.isProximityMonitoringEnabled = true
if UIDevice.current.isProximityMonitoringEnabled {
NotificationCenter.default.addObserver(proximityObserver, selector: #selector(proximityObserver.didChange), name: UIDevice.proximityStateDidChangeNotification, object: UIDevice.current)
}
}
func deactivateProximitySensor() {
print("MyView::deactivateProximitySensor")
UIDevice.current.isProximityMonitoringEnabled = false
NotificationCenter.default.removeObserver(proximityObserver, name: UIDevice.proximityStateDidChangeNotification, object: UIDevice.current)
}
var body: some View {
Text("Foo")
.onAppear() {
self.activateProximitySensor()
}.onDisappear() {
self.deactivateProximitySensor()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment