Short: I don't know how to extract the CMRecordedAccelerometerData from the CMSensorDataList after getting one from the CMSensorRecorder. Apple isn't providing any documentation, yet.
Maybe someone has a hint for me? ;)
func startMovementDetection(){
var accDataList = self.cmSensorRecorder!.accelerometerDataFrom(self.startDate, to: NSDate()) as CMSensorDataList
CMRecordedAccelerometerData() //that's the class i want to extract from CMSensorDataList
}
Okay, problem solved with this one here: NSFastEnumeration in Swift
With Swift 3.0 it changes to:
extension CMSensorDataList: Sequence {
public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}
//First make the extension tu use enumerate in the for-in loop
extension CMSensorDataList: SequenceType {
public func generate() -> NSFastGenerator {
return NSFastGenerator(self)
}
}
//Now you can query the recorded data
func printData(){
let date = NSDate()
let recorder = CMSensorRecorder()
let sensorData: CMSensorDataList = recorder.accelerometerDataFromDate(initialDate!, toDate: date)!
for (index, data) in sensorData.enumerate() {
print(index, data)
}
}
Here's a Swift 4 approach. First, you’ll need to make CMSensorDataList conform to Sequence by means of an extension:
extension CMSensorDataList: Sequence {
public typealias Iterator = NSFastEnumerationIterator
public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}
Now you can iterate over CMSensorDataList to obtain CMRecordedAccelerometerData instances, each consisting of a timestamp
and an acceleration
:
let rec = CMSensorRecorder() // and d1 and d2 are Dates
if let list = rec.accelerometerData(from: d1, to: d2) {
for datum in list {
if let accdatum = datum as? CMRecordedAccelerometerData {
let accel = accdatum.acceleration
let t = accdatum.timestamp
// do something with data here
}
}
}
Marcus's answer in Swift 4:
//First make the extension to use enumerate in the for-in loop
extension CMSensorDataList: Sequence {
public typealias Iterator = NSFastEnumerationIterator
public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}
//Now you can query the recorded data
func printData(){
let date = Date()
let recorder = CMSensorRecorder()
let accelerometerData = recorder.accelerometerData(from: startDate, to: endDate)
for (index, data) in (accelerometerData?.enumerated())! {
print(index, data)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With