2016-11-02 1 views
2

J'ai le code suivant d'Objective-C, ça marche très bien.Swift 3 CMMotionManager startGyroMises à jour ne fonctionne pas

_motionManager = [[CMMotionManager alloc] init]; 
_motionManager.gyroUpdateInterval = 1.0/60.0; 

[_motionManager startGyroUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMGyroData *gyroData, NSError *error) 
{ 

     xAcceleration = gyroData.rotationRate.x; 
     yAcceleration = gyroData.rotationRate.y; 

    [self acceleratorUpdates]; 

}]; 

Et j'ai essayé de le convertir en Swift 3 mais cela ne fonctionne pas, il donne toutes sortes d'erreurs. Jusqu'à présent, j'ai obtenu ce code.

let motionManager = CMMotionManager() 

    motionManager.gyroUpdateInterval = 1.0/60.0 


    motionManager.startGyroUpdates(to: OperationQueue.current!, withHandler: {(gyroData: CMGyroData, error: Error) 
     var xAcceleration = gyroData.rotationRate.x 
     var yAcceleration = gyroData.rotationRate.y 

     print("xAcceleration: ", xAcceleration, "yAcceleration: ", yAcceleration) 
    }) 

Je pense qu'il me manque quelque chose dans la partie withHandler. La documentation a dit ceci: -> Annuler après le gestionnaire, mais cela n'a pas aidé. Tous les codes du web sont Swift 2.

+1

Cela a fonctionné après avoir fait 'motionManager' en tant que variable d'instance. –

Répondre

0

essayer cela dans une méthode de votre classe:

// data members: 
private var gyroPresent = false 
private var manager : CMMotionManager? 

..

self.manager = CMMotionManager() 
guard self.manager != nil else { 
    // never here.. but... to be sure. 
    print("no CMMotionManager") 
    return 
} 

self.gyroPresent = self.manager!.isGyroAvailable 
guard self.gyroPresent else { 
    print("no GyroScope") 
    return 
} 

self.manager!.gyroUpdateInterval = 0.1 

// remember to stop it.. with:  self.manager?.stopGyroUpdates() 
self.manager!.startGyroUpdates(to: OperationQueue.main) { (data: CMGyroData?, error: Error?) in 
    if let info = data?.rotationRate{ 
      print("\(info.x) \(info.z) \(info.z) ") 
     } 
    } 

... 

testé sur Xcode 8.2.1/3.x rapide et le dispositif iOS 10.2.1 (14D27)

PS assurez-vous d'utiliser la liste de capture pour éviter de retenir en cas d'utilisation des cycles auto:

{ [unowned self] in 
    ... 
}