2014-06-09 21 views
9

Tôi đang cố gắng sử dụng trình quản lý chuyển động trong Swift nhưng nhật ký bên trong khối cập nhật của tôi không bao giờ được in.Trình quản lý chuyển động không hoạt động trong Swift

var motionManager: CMMotionManager = CMMotionManager() 
    motionManager.accelerometerUpdateInterval = 0.01 
    println(motionManager.deviceMotionAvailable) // print true 
    println(motionManager.deviceMotionActive) // print false 
    motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:{ 
     deviceManager, error in 
     println("Test") // no print 
    }) 

    println(motionManager.deviceMotionActive) // print false  

Thực hiện mục tiêu-C của tôi hoạt động tốt. Có ai biết tại sao khối cập nhật của tôi không được gọi?

Trả lời

22

Đó là do trường hợp trình quản lý chuyển động đang bị loại bỏ khi phương thức trả về. Bạn nên tạo một thuộc tính trên lớp của bạn để chứa trình quản lý chuyển động. Ngoài ra, có vẻ như bạn chỉ đang thay đổi accelerometerUpdateInterval của người quản lý và sau đó theo dõi các thay đổi chuyển động của thiết bị. Thay vào đó, bạn nên đặt thuộc tính deviceMotionUpdateInterval.

import CoreMotion 

class ViewController: UIViewController { 
    let motionManager = CMMotionManager() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     motionManager.deviceMotionUpdateInterval = 0.01 
     motionManager.startDeviceMotionUpdates(to: OperationQueue.current!) { deviceManager, error in 
      print("Test") // no print 
     } 

     print(motionManager.isDeviceMotionActive) // print false 
    } 
} 
0

Tôi nghĩ rằng tất cả các biến obj-c là optionals trong nhanh chóng (kể từ khi họ có thể bằng không) để NSOperationQueue nên một tiếng nổ thusly:

MotionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue!.currentQueue(),withHandler:{deviceManager,error in println("test")}) 

của Apple tài liệu ở đây:

https://developer.apple.com/library/ios/documentation/CoreMotion/Reference/CMMotionManager_Class/#//apple_ref/swift/tdef/CMDeviceMotionHandler

Hoa

Loại o f block callback để xử lý dữ liệu chuyển động thiết bị.

Tuyên bố SWIFT typealias CMDeviceMotionHandler = (CMDeviceMotion !, NSError!) -> Void

Các vấn đề liên quan