2016-06-19 32 views
5

Sto cercando di ottenere il movimento del dispositivo (pitch, roll, imbardata) ma la mia funzione handleDeviceMotionUpdate non viene avviata (sto provando su un iphone 5s), ecco il codice:motion manager non funziona

import UIKit 
import CoreMotion 

class ViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 






    var motionManager = CMMotionManager() 
    motionManager.startDeviceMotionUpdates() 
    motionManager.deviceMotionUpdateInterval = 0.1 


    motionManager.startDeviceMotionUpdatesToQueue(
     NSOperationQueue.currentQueue()!, withHandler: { 
      (deviceMotion, error) -> Void in 

      if(error == nil) { 
       self.DeviceMotionUpdate(deviceMotion!) 
      } else { 
       print("error") 
      } 
    }) 

} 


override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 

} 

func DeviceMotionUpdate(deviceMotion:CMDeviceMotion) { 
    print("function launched") 
    var attitude = deviceMotion.attitude 
    var roll = (attitude.roll) 
    var pitch = (attitude.pitch) 
    var yaw = (attitude.yaw) 
    print("Roll: \(roll), Pitch: \(pitch), Yaw: (yaw)") 

} 



} 

Non viene visualizzato l'errore in startDeviceMotionUpdatesToQueue. Vero diventa true su motionManager.deviceMotionActive e su motionManager.deviceMotionAvailable

risposta

6

Il tuo motionManager probabilmente viene distrutto dopo aver terminato l'esecuzione del metodo viewDidLoad. Prova a trasformare motionManager in una proprietà di classe.

class ViewController: UIViewController { 
    var motionManager = CMMotionManager() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.motionManager.startDeviceMotionUpdates() 

     ... 
+0

oh grazie ha funzionato! – Theilya