Swift中的接近传感器(来自Objective-C)

Swift中的接近传感器(来自Objective-C),第1张

概述我是一个相对较新的快速用户,现在,我需要利用iPhone的接近传感器.我跟距离无关,但我想知道iPhone附近有什么东西. 所以我在Objective-C中找到了这个代码,但是我在Swift中需要它.我尝试了一些方法,但任何方法都有效.所以这是我需要的代码: - (void) activateProximitySensor { UIDevice *device = [UIDevice cu 我是一个相对较新的快速用户,现在,我需要利用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}

我在执行应用程序时始终执行的功能.

编辑2:尝试Eric D.评论的代码

let sensor = MySensor() //declared in the VC but globallyoverrIDe 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!")    }}
总结

以上是内存溢出为你收集整理的Swift中的接近传感器(来自Objective-C)全部内容,希望文章能够帮你解决Swift中的接近传感器(来自Objective-C)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1089981.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存