Skip to content

Instantly share code, notes, and snippets.

@elpsk
Last active May 19, 2023 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elpsk/2d01da837aefc81f3e4b386e04a4b972 to your computer and use it in GitHub Desktop.
Save elpsk/2d01da837aefc81f3e4b386e04a4b972 to your computer and use it in GitHub Desktop.
Swift - Proximity sensor (shut down screen if near ear)
//
// ProximityVC.swift
// Created by Pasca Alberto, IT on 10/08/18.
// Copyright © 2018 albertopasca.it. All rights reserved.
//
import UIKit
class ProximityVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
activateProximitySensor()
}
func activateProximitySensor() {
let device = UIDevice.current
device.isProximityMonitoringEnabled = true
if device.isProximityMonitoringEnabled {
NotificationCenter.default.addObserver(
self,
selector: #selector(proximityChanged),
name: UIDevice.proximityStateDidChangeNotification,
object: device
)
}
}
@objc func proximityChanged(notification: NSNotification) {
if let device = notification.object as? UIDevice {
print("proximity: \(device.proximityState)")
}
}
}
@mehulparmar4ever
Copy link

Hello Please update code

if device.isProximityMonitoringEnabled {
			NotificationCenter.default.addObserver(
				self,
				selector: #selector(proximityChanged),
				name: UIDevice.proximityStateDidChangeNotification,
				object: device
			)
		}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment