본문 바로가기
Apple/iOS

[iOS] 근접 센서 사용하기

by 어멘드 2022. 7. 12.
반응형

 통화할 때 기기를 귀 가까이에 가져다 대면 화면이 검게 변하고, 귀에서 떼면 다시 통화 화면이 표시된다.
 근접 센서를 이용해서 구현된 기능으로, 근접 센서 가까이에 물체가 감지되면 화면이 저절로 어둡게 변한다.
 앱에서도 근접 센서를 사용할 수 있다.


Proximity Monitoring

 UIDevice 클래스에 인스턴스 프로퍼티로 근접 모니터링 활성화 여부가 구현되어 있다.

var isProximityMonitoringEnabled: Bool { get set }

 

 디폴트 값은 false이기 때문에, 근접 센서를 사용하고자 한다면 true로 활성화시켜 주어야 한다.
 근접 센서를 활성화시키기만 하면, 근접 센서에 물체가 감지되면 화면이 어두워지는 기능이 저절로 동작된다.

UIDevice.current.isProximityMonitoringEnabled = true

 

 하지만 모든 iOS 디바이스에 근접 센서가 있는 것은 아니다.
 공식 문서에 따르면 현재 기기에서 근접 센서 사용이 가능한지 체크하는 방법은 아래와 같다.

func checkIfProximitySensorIsAvailable() -> Bool {
    // 1. 근접 센서를 활성화시킨다.
    UIDevice.current.isProximityMonitoringEnabled = true
    defer {
        UIDevice.current.isProximityMonitoringEnabled = false
    }
	
    // 2. 근접 센서 활성화 상태를 체크한다.
    if UIDevice.current.isProximityMonitoringEnabled {
        return true     // 2-1. 활성화 상태이면 근접 센서 사용 가능 기기
    } else {
        return false    // 2-2. 활성화를 해주었는데도 계속 비활성화 상태이면 근접 센서 사용 불가 기기
    }
}

Proximity State

 근접 센서에서 감지하고 있는 상태에 대한 값도 읽어올 수 있다.
 마찬가지로 UIDevice 클래스에 인스턴스 프로퍼티로 구현되어 있다.
 true일 때가 근접 센서 근처에 물체가 감지된 상태이고, 반대로 false인 경우는 가까이에 물체가 없는 상태이다.

var proximityState: Bool { get }

 

 만약 근접 센서에 감지된 값을 가지고 별도의 로직을 짜고 싶다면 UIDevice.proximityStateDidChangeNotification을 이용하면 된다.

NotificationCenter.default.addObserver(self, selector: #selector(proximityStateDidChange), name: UIDevice.proximityStateDidChangeNotification, object: nil)
@objc func proximityStateDidChange() {
    print("\(UIDevice.current.proximityState ? "물체가 가까이 감지되었습니다." : "물체가 멀어졌습니다.")")
}

> 레퍼런스

https://developer.apple.com/documentation/uikit/uidevice/1620017-isproximitymonitoringenabled

https://developer.apple.com/documentation/uikit/uidevice/1620058-proximitystate

반응형

댓글