Swift 中的接近传感器(来自 Objective-C) [英] Proximity sensor in Swift (from Objective-C)

查看:85
本文介绍了Swift 中的接近传感器(来自 Objective-C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个相对较新的 swift 用户,现在我需要利用 iPhone 的接近传感器.我不关心距离,但我想知道什么时候有东西靠近 iPhone.

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 near the iPhone.

所以我在 Objective-C 中发现这段代码有效,但我在 Swift 中需要它.我尝试了一些方法,但任何方法都有效.所以这是我需要的代码:

So I found this code in Objective-C that worked, but I need it in Swift. I have tried some ways, but any worked. So here is the code I need:

- (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
}

我在函数中放入的内容总是在应用程序执行时执行.

What I put in the function it's executed always when the app is executed.

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

EDIT 2: Trying the code of Eric D. comment

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!")
    }
}

这篇关于Swift 中的接近传感器(来自 Objective-C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆