Proximity sensor in Swift (from Objective-C) -


i'm relatively new user swift , now, need take advantage of proximity sensor of iphone. don't matter distance, want know when near iphone.

so found code in objective-c worked, need in swift. have tried ways, worked. here code 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 want } 

edit 1: tried this:

override func viewdidload() {         super.viewdidload()         uidevice.currentdevice().proximitymonitoringenabled = true;          nsnotificationcenter.defaultcenter().addobserver(self, selector: selector(proximitystatedidchange()), name:uideviceproximitystatedidchangenotification, object: nil); } 

and function:

func proximitystatedidchange() {         //do whatever want } 

what put in function it's executed when app executed.

edit 2: trying code of eric d. comment

let sensor = mysensor() //declared in vc globally  override func viewdidload() {         super.viewdidload()         sensor.activateproximitysensor() } 

throws me exception: exception xcode throw me

hope can help,

thanks in advance!

here's take on this.

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

Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -