Proximity sensor in Swift (from Objective-C)

前端 未结 5 1105
死守一世寂寞
死守一世寂寞 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:04

    Finally I get it working with the answer of Eric D.

    Here is the code:

    func proximityChanged(notification: NSNotification) {
      if let device = notification.object as? UIDevice {
        println("\(device) detected!")
      }
    }
            
    func activateProximitySensor() {
      let device = UIDevice.currentDevice()
      device.proximityMonitoringEnabled = true
      if device.proximityMonitoringEnabled {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "proximityChanged:", name: "UIDeviceProximityStateDidChangeNotification", object: device)
        }
      }
    }
    

    and in the viewDidLoad:

    override func viewDidLoad() {
      super.viewDidLoad()
      activateProximitySensor()
    }
    

    Hope it helps!

提交回复
热议问题