我是一个相对较新的快速用户,现在,我需要利用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
}
Run Code Online (Sandbox Code Playgroud)
编辑1:我试过的是这样的:
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.currentDevice().proximityMonitoringEnabled = true;
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(proximityStateDidChange()), name:UIDeviceProximityStateDidChangeNotification, object: nil);
}
Run Code Online (Sandbox Code Playgroud)
和功能:
func proximityStateDidChange() {
//DO WHATEVER I WANT
}
Run Code Online (Sandbox Code Playgroud)
我在执行应用程序时始终执行的功能.
编辑2:尝试Eric D.评论的代码
let sensor = MySensor() //declared in the …
Run Code Online (Sandbox Code Playgroud)