我是一个相对较新的快速用户,现在,我需要利用iPhone的接近传感器.我跟距离无关,但我想知道iPhone附近有什么东西.
所以我在Objective-C中找到了这个代码,但是我在Swift中需要它.我尝试了一些方法,但任何方法都有效.所以这是我需要的代码:
- (void) activateProximitySensor { UIDevice *device = [UIDevice currentDevice]; device.proximityMonitoringEnabled = YES; if (device.proximityMonitoringEnabled == YES) { [[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(proximityChanged:) name:@"UIDeviceProximityStateDidChangeNotification" object:device]; } } - (void) proximityChanged:(NSNotification *)notification { UIDevice *device = [notification object]; NSLog(@"Detectat"); //DO WHATEVER I WANT }
编辑1:我试过的是这样的:
override func viewDidLoad() { super.viewDidLoad() UIDevice.currentDevice().proximityMonitoringEnabled = true; NSNotificationCenter.defaultCenter().addobserver(self,selector: Selector(proximityStateDidChange()),name:UIDeviceProximityStateDidChangeNotification,object: nil); }
和功能:
func proximityStateDidChange() { //DO WHATEVER I WANT }
我在执行应用程序时始终执行的功能.
let sensor = MySensor() //declared in the VC but globally override func viewDidLoad() { super.viewDidLoad() sensor.activateProximitySensor() }
抛出我的异常:
希望有人能提供帮助,
提前致谢!
这是我对此的看法.
func activateProximitySensor() { let device = UIDevice.currentDevice() device.proximityMonitoringEnabled = true if device.proximityMonitoringEnabled { NSNotificationCenter.defaultCenter().addobserver(self,selector: "proximityChanged:",name: "UIDeviceProximityStateDidChangeNotification",object: device) } } func proximityChanged(notification: NSNotification) { if let device = notification.object as? UIDevice { println("\(device) detected!") } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。