Jerry  Xu Jerry Xu - 6 months ago 27
iOS Question

iOS9 error on activityManager.startActivityUpdatesToQueue

I opened my app in the new Xcode7 beta which worked perfectly fine in older version. Now I'm receiving errors, and i don't know how to solve it. Here is the code. Error is commented out.

import UIKit
import CoreMotion
class ViewController: UIViewController {

let activityManager = CMMotionActivityManager()
let pedoMeter = CMPedometer()

@IBOutlet weak var activityState: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

if(CMMotionActivityManager.isActivityAvailable()){
print("YESS!")
self.activityManager.startActivityUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: {(data: CMMotionActivity!) -> Void in //Cannot invoke 'startActivityUpdatesToQueue' with an argument list of type '(NSOperationQueue, withHandler: (CMMotionActivity!) -> Void)'
dispatch_async(dispatch_get_main_queue(), {() -> Void in
if(data.stationary == true){
self.activityState.text = "Stationary"
} else if (data.walking == true){
self.activityState.text = "Walking"
} else if (data.running == true){
self.activityState.text = "Running"
} else if (data.automotive == true){
self.activityState.text = "Automotive"
}

})
})
}

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}

Answer

The problem is the data type CMMotionActivity? not CMMotionActivity!

Here is something that should work for you:

 if(CMMotionActivityManager.isActivityAvailable()){
        print("YES!")
        self.activityManager.startActivityUpdatesToQueue(NSOperationQueue.mainQueue()) { data in
            if let data = data {
                dispatch_async(dispatch_get_main_queue()) {
                    if(data.stationary == true){
                        self.activityState.text = "Stationary"
                    } else if (data.walking == true){
                        self.activityState.text = "Walking"
                    } else if (data.running == true){
                        self.activityState.text = "Running"
                    } else if (data.automotive == true){
                        self.activityState.text = "Automotive"
                    }
                }
            }
        }
    }

Also try to take advantage of last argument is a closure to simplify the function calls.

Comments