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.
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
}
EDIT 1: What I tried was this:
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.currentDevice().proximityMonitoringEnabled = true;
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(proximityStateDidChange()), name:UIDeviceProximityStateDidChangeNotification, object: nil);
}
and the function:
func proximityStateDidChange() {
//DO WHATEVER I WANT
}
What I put in the function it's executed always when the app is executed.
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()
}
Throws me the exception:
Hope someone can help,
Thanks in advance!
let sensor = MySensor()
insideviewDidLoad
, but as soon asviewDidLoad
ends its execution, yoursensor
is freed from memory, and later when the notification observer fires the notification, it can't find your object, so it crashes. You should declarelet sensor = MySensor()
outside ofviewDidLoad
, either globally or in a class you can reach anytime. – Megdalsensor
firing when the object has been released. If my code didn't work at all, the notification wouldn't be triggered and nothing would happen (no crash, just nothing). I hope you will find a solution, I'm curious about this. – MegdalproximityChanged
elsewhere (not in the MySensor class). Also try by usingactivateProximitySensor
not insideMySensor
. Maybe adding the two funcs in a class like I did is the problem (in your example the two funcs weren't included in their own class). – Megdal