Proximity sensor in Swift (from Objective-C)

前端 未结 5 991
死守一世寂寞
死守一世寂寞 2021-02-14 18:45

I\'m a relatively new user to swift and now, I need to take advantage of the proximity sensor of an iPhone. I don\'t matter the distance, but I want to know when something is ne

5条回答
  •  忘掉有多难
    2021-02-14 19:10

    Swift 4.2

    Activate or deactivate ProximitySensor:

    func activateProximitySensor(isOn: Bool) {
        let device = UIDevice.current
        device.isProximityMonitoringEnabled = isOn
        if isOn {
            NotificationCenter.default.addObserver(self, selector: #selector(proximityStateDidChange), name: UIDevice.proximityStateDidChangeNotification, object: device)
        } else {
            NotificationCenter.default.removeObserver(self, name: UIDevice.proximityStateDidChangeNotification, object: device)
        }
    }
    

    Selector:

    @objc func proximityStateDidChange(notification: NSNotification) {
        if let device = notification.object as? UIDevice {
            print(device)
        }
    }
    

提交回复
热议问题