首页 > 解决方案 > 这意味着什么:“线程 1:”-[First_App.ProximitySensorViewControllerproximityChanged:]:无法识别的选择器发送到实例 0x14d707940“”

问题描述

嘿,我正在尝试使用接近传感器来增加一个值,但是当我启动该功能时,它会崩溃。这是我的代码,有人可以帮助我吗?

func proximityChanged(notification: NSNotification) {
            let device = notification.object as? UIDevice
            if device?.proximityState == true {
                print("\(device) detected!")
                count += 1
                updateCountLabel()
            } else {
                print("Error")
            }
        }
        
        
        func activateProximitySensor() {
            let device = UIDevice.current
            device.isProximityMonitoringEnabled = true
            if device.isProximityMonitoringEnabled {
                NotificationCenter.default.addObserver(self, selector: Selector(("proximityChanged:")), name: NSNotification.Name(rawValue: "UIDeviceProximityStateDidChangeNotification"), object: device)
                
            }
        }

标签: swiftsensorsproximitysensor

解决方案


我认为您可能正在使用旧语法来实现 swift。我尝试使用下面的代码使用邻近度,并且工作时没有崩溃。

func activateProximitySensor() {
    let device = UIDevice.current
    device.isProximityMonitoringEnabled = true
    if device.isProximityMonitoringEnabled {
        NotificationCenter.default.addObserver(self, selector: #selector(proximityChanged(notification:)), name: UIDevice.proximityStateDidChangeNotification, object: device)
    }
}

@objc func proximityChanged(notification: NSNotification) {
    if let device = notification.object as? UIDevice {
        if device.proximityState {
            print("\(device) detected!")
            count += 1
            updateCountLabel()
        }
    }
}

推荐阅读