Core Motion

RSS for tag

Process accelerometer, gyroscope, pedometer, and environment-related events using Core Motion.

Core Motion Documentation

Posts under Core Motion tag

41 results found
Sort by:
Post not yet marked as solved
56 Views

CoreMotion Aligning IPhones CMAttitude

I'm doing a simple experiment with 2 iphones. I've made a simple app that subscribes to device motion updates (with reference frame xTrueNorthZVertical). I've aligned the phones to be close to the same rotation (it can't be more than 3-4 degrees). Generally regardless of how I move the phones roll and pitch match up well on both phones. The yaw, however, always has a discrepancy between the 2 devices. This can be 15 to 45 degrees depending on the run and the position I've moved them to. Is my assumption that the roll, pitch, and yaw of CMAttitude should more or less match up if I'm holding them in the same rotation (more or less) relative to the reference frame (which I've set to be the same and not arbitrary). Is there a certain degree of error I should be aware of or are there other settings I should be looking into? Here's a small code snippet of my settings: self.motion.deviceMotionUpdateInterval = 1.0 self.motion.showsDeviceMovementDisplay = true self.motion.startDeviceMotionUpdates(using: .xTrueNorthZVertical) The magnetic field accuracy always reads "high"
Asked
by tonyl7127.
Last updated
.
Post marked as solved
241 Views

Activity recognition using core motion

as i want to tract activity of iphone user using core motion framework , guide me through .
Asked Last updated
.
Post not yet marked as solved
123 Views

player not moving when tilting

Code seems fine however when i run the simulator in xcode or on my phone and tilt, the player doesnt move. override func update(_ currentTime: TimeInterval) {     if let accelerometerData = motionManager?.accelerometerData {       physicsWorld.gravity = CGVector(dx: accelerometerData.acceleration.x * -50, dy: accelerometerData.acceleration.y * 50)     } Do i need gamescene.sks because i deleted the grid and the file
Asked
by nathandr.
Last updated
.
Post marked as solved
176 Views

Xcode Swift Coremotion Pedometer update every step

Hello! Does anyone know if there is a way for the CoreMotion Pedometer to update every step? As it is, it always seems to take a certain amount of time/steps to update, even when force started. I've also been trying to find workarounds (with other pedometers, it is sometimes possible to grab the "signal" and count that), but none have worked. Is this outside of CoreMotion's scope? Does anyone have any other suggestions or workarounds? Thank you!
Asked Last updated
.
Post not yet marked as solved
159 Views

WatchOS continuous reading of core motion data

I am trying to read core motion data (accel, gyro) and store them using my iWatch 6 for an extended amount of time (about 14 days). So, I realize that my application becomes unresponsive. I looked into it and I think that the watchdog kills my application because I am constantly writing stuff in OperationQueue.current! .To extract data from this queue, I need to get the foreground. So, I thought that my best bet would be to schedule a task and call it every ~30 min to do that for me. But when I schedule a task, it keeps happening for the first couple of times and then becomes very sporadic (maybe every 10 hours instead of 30 min). So, I am just looking for a way to do such an EASY task. Since I was not able to use the scheduleBackgroundRefresh, I am using the locationmanager as an alternative (just like a timer) as it can run in the background. I know that it is not the best practice but I could not find any other way around this. To save the battery, I used the reduced accuracy which collects the location every 15 minutes or so. This runs great up until 8 hours. Then it becomes sporadic again! I am not sure what to do with that. // // ExtensionDelegate.swift // STMITest WatchKit Extension import WatchKit import CoreMotion class ExtensionDelegate: NSObject, WKExtensionDelegate, CLLocationManagerDelegate {   let motionManagerDelegate = CMMotionManager()   let locationManager:CLLocationManager = CLLocationManager()       var sensorTime=[Double]()   var sensorRx=[Double]()   var sensorRy=[Double]()   var sensorRz=[Double]()   var offsetTime=0.0   var offsetTimeFlag=true       var lastSyncedDate=Date()   var locationStartDate=Date()       func applicationDidFinishLaunching() {     print("Delegate:App finished lunching")           locationConfig()     locationStarter()           lastSyncedDate=Date()     locationStartDate=Date()   }           func locationConfig(){     print("LocationConfig Func")     locationManager.delegate=self     locationManager.desiredAccuracy = kCLLocationAccuracyReduced     locationManager.allowsBackgroundLocationUpdates=true     locationManager.activityType = .fitness   }       func locationStarter(){     if locationManager.authorizationStatus == .authorizedWhenInUse || locationManager.authorizationStatus == .authorizedAlways{       print("-------------initiation-authority is ok")       locationManager.startUpdatingLocation()     }     else{       print("-------------initiation-authority is changing")       locationManager.requestWhenInUseAuthorization()     }   }       func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {     if locations.first != nil {       print("location:: \(locations)")     }     startQueuedMotionUpdates()     var timeInterval=Date().timeIntervalSince(lastSyncedDate)     if timeInterval > 1 * 60{       binaryWriter("GPSSuccess")       lastSyncedDate=Date()     }     timeInterval=Date().timeIntervalSince(locationStartDate)     if timeInterval > 3 * 60 * 60{       locationManager.stopUpdatingLocation()       locationManager.startUpdatingLocation()     }   }       func locationManager(_ manager: CLLocationManager, didFailWithError error: Error ) {     print("Error in location manager")     startQueuedMotionUpdates()     var timeInterval=Date().timeIntervalSince(lastSyncedDate)     if timeInterval > 1 * 60{       binaryWriter("GPSError")       lastSyncedDate=Date()     }     timeInterval=Date().timeIntervalSince(locationStartDate)     if timeInterval > 3 * 60 * 60{       locationManager.stopUpdatingLocation()       locationManager.startUpdatingLocation()     }   }       func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {     print("authority should change",self.locationManager.authorizationStatus)     switch manager.authorizationStatus {     case .restricted, .denied, .notDetermined:       print("restricted, denied or notDetermined")       locationManager.requestWhenInUseAuthorization()       break             case .authorizedAlways:       print("always on")       break                case .authorizedWhenInUse:       print("only when it is in use")       locationManager.startUpdatingLocation()     }   }     //  func taskScheduler(){ //    let fireDate=Date(timeIntervalSinceNow: 60*60) //    let wkExt = WKExtension.shared() //    let info: NSDictionary = ["Caller": "to update motion"] //    wkExt.scheduleBackgroundRefresh(withPreferredDate: fireDate,userInfo:info) { (error: Error?) in if (error != nil) { //      print("background refresh could not be scheduled.") //    } //    else{ //      print("successfully scheduled") //    } //    } // //  }       func startQueuedMotionUpdates() {     if self.motionManagerDelegate.isDeviceMotionAvailable {       if !motionManagerDelegate.isDeviceMotionActive{         motionManagerDelegate.deviceMotionUpdateInterval = 30.0 / 60.0         motionManagerDelegate.showsDeviceMovementDisplay = true       }       motionManagerDelegate.startDeviceMotionUpdates(using: .xMagneticNorthZVertical, to: OperationQueue.current!, withHandler: { (data, error) in           if let validData = data {             let rX = validData.rotationRate.x             let rY = validData.rotationRate.y             let rZ = validData.rotationRate.z                           let aX = validData.userAcceleration.x             let aY = validData.userAcceleration.y             let aZ = validData.userAcceleration.z                           let timeStamp=validData.timestamp             if self.offsetTimeFlag{               self.offsetTime = 0.0-timeStamp               self.offsetTimeFlag=false             } //            self.sensorTime.append(contentsOf: [timeStamp+self.offsetTime])             self.sensorTime.append(contentsOf: [timeStamp+self.offsetTime,rX,rY,rZ,aX,aY,aZ])           }         })     }     else {       fatalError("The motion data is not avaialable")     }   }       func binaryWriter(_ extensionName: String) {     var myDate = Date()     let dateFormatter = DateFormatter()     dateFormatter.dateFormat = "dd-HH:mm:ss"     var currentTime = dateFormatter.string(from: myDate)     var fileName = currentTime+extensionName           print("Writing Start========================",fileName)     if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {       do {         fileName = currentTime+extensionName+"Time"         var fileURL = dir.appendingPathComponent(fileName)         try (self.sensorTime as NSArray).write(to: fileURL,atomically: true)         self.sensorTime.removeAll()                 }       catch{         print("Error in the binaryWriter Function")       }     }     myDate = Date()     currentTime = dateFormatter.string(from: myDate)     print("Writing End========================",currentTime)   } }
Asked
by Sorush.
Last updated
.
Post marked as solved
159 Views

Gyroscope and Magnometer Data on Apple Watch

Hi I am having an issue accessing gyroscope and magnometer data through CoreMotion. I have an apple watch 6 (os 7.6), iPhone XS max (ios 14.7) and XCode 12.5.1. I did write a simple application to print the accel, gyro and magno data. It works on the phone but not on the watch. On the watch, it only gives me accel data and when I do isGyroAvailable or isMagnoAvailable I get False, while isAccelAvailable gives me True. Should I turn on something? Maybe an authentication flag? Any help will be greatly appreciated.
Asked
by Sorush.
Last updated
.
Post not yet marked as solved
129 Views

iWatch application got killed

Hi I am pretty new to ios development and I am trying to write a code to store the acceleration and gyro data into files using iwatch se (OS 7.5), iPhone XSMax (14.7.1) and XCode 12.5.1. I wrote most of my application in the ExtensionDelegate which I put below. The application gets killed after a couple of hours. Any ideas why? I think the watchdog kills it. I know this is not the most efficient way to write it but I was unable to make the timer thing working in the background! :( import WatchKit import CoreMotion class ExtensionDelegate: NSObject, WKExtensionDelegate {   let motionManagerDelegate = CMMotionManager()   var sensorDataDelegate=[Double]()   var offsetTime=0.0   var offsetTimeFlag=true       func applicationDidFinishLaunching() {     print("Delegate:App finished lunching")     self.startQueuedMotionUpdates()   }   func applicationDidBecomeActive() {     print("Delegate:App active") //    self.startQueuedMotionUpdates()     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.   }   func applicationWillResignActive() {     print("Delegate:App will be active") //    self.startQueuedMotionUpdates()     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.     // Use this method to pause ongoing tasks, disable timers, etc.   }       func applicationDidEnterBackground() {     print("Delegate:App is background") //    self.startQueuedMotionUpdates()     self.binaryWriter()   }       func applicationWillEnterForeground() {     print("Delegate:App will be foreground") //    self.startQueuedMotionUpdates()   }           func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {     // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.     self.startQueuedMotionUpdates()     self.binaryWriter()     for task in backgroundTasks {       // Use a switch statement to check the task type       switch task {         case let backgroundTask as WKApplicationRefreshBackgroundTask:           // Be sure to complete the background task once you’re done.           backgroundTask.setTaskCompletedWithSnapshot(false)         case let snapshotTask as WKSnapshotRefreshBackgroundTask:           // Snapshot tasks have a unique completion call, make sure to set your expiration date           snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)         case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:           // Be sure to complete the connectivity task once you’re done.           connectivityTask.setTaskCompletedWithSnapshot(false)         case let urlSessionTask as WKURLSessionRefreshBackgroundTask:           // Be sure to complete the URL session task once you’re done.           urlSessionTask.setTaskCompletedWithSnapshot(false)         case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:           // Be sure to complete the relevant-shortcut task once you're done.           relevantShortcutTask.setTaskCompletedWithSnapshot(false)         case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:           // Be sure to complete the intent-did-run task once you're done.           intentDidRunTask.setTaskCompletedWithSnapshot(false)         default:           // make sure to complete unhandled task types           task.setTaskCompletedWithSnapshot(false)       }     }   }   func startQueuedMotionUpdates() {     var myDate = Date()     var dateFormatter = DateFormatter()     dateFormatter.dateFormat = "yyyy-MM-dd-HH:mm:ss"     var currentTime = dateFormatter.string(from: myDate)                 print("sensor function starts==============================",currentTime)           if self.motionManagerDelegate.isDeviceMotionAvailable {       if !self.motionManagerDelegate.isDeviceMotionActive{         self.motionManagerDelegate.deviceMotionUpdateInterval = 30 / 60.0         self.motionManagerDelegate.showsDeviceMovementDisplay = true       }         self.motionManagerDelegate.startDeviceMotionUpdates(using: .xMagneticNorthZVertical, to: OperationQueue.current!, withHandler: { (data, error) in           if let validData = data {             let rX = validData.rotationRate.x             let rY = validData.rotationRate.y             let rZ = validData.rotationRate.z             let timeStamp=validData.timestamp             if self.offsetTimeFlag{ //              let currentTime=Date().timeIntervalSince1970 //              self.offsetTime=currentTime-timeStamp               self.offsetTime = 0.0-timeStamp               self.offsetTimeFlag=false             }             self.sensorDataDelegate.append(contentsOf: [timeStamp+self.offsetTime])           }         })     }     else {       fatalError("The motion data is not avaialable")     }     myDate = Date()     currentTime = dateFormatter.string(from: myDate)     print("sensor function ends==============================",currentTime)   }       func binaryWriter() {     var tempVal = self.sensorDataDelegate     var myDate = Date()     var dateFormatter = DateFormatter()     dateFormatter.dateFormat = "MM-dd-HH:mm:ss"     var fileName = dateFormatter.string(from: myDate)           print("Writing Start========================",fileName)     if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {       let fileURL = dir.appendingPathComponent(fileName)       do {         try (tempVal as NSArray).write(to: fileURL,atomically: true)       }       catch {/* error handling here */}     }           myDate = Date()     var currentTime = dateFormatter.string(from: myDate)     print("Writing End========================",currentTime)     self.sensorDataDelegate.removeAll()     myDate = Date()     currentTime = dateFormatter.string(from: myDate)     print("Data is cleaned========================",currentTime)   }     }
Asked
by Sorush.
Last updated
.
Post not yet marked as solved
250 Views

Sample Rate Bug in CreateML App

Create a sample project in Creat ML and choose Activity Classifier. When lowering the sample rate, the preview timeline gets shorter instead of getting longer. Furthermore, it seems the entire preview timeline breaks (can't scroll) if the sample rate is anything other than 50. Try it out: Train a model with sample rate 50, then try training it with sample rate 10.
Asked
by jakemor.
Last updated
.
Post not yet marked as solved
344 Views

How to simulate Fall Detection events with WatchOS Simulator?

In the documentation for CMFallDetectionManager and CMFalDetectionDelegate in XCode, there is a comment that says, "Fall Detection events can be simulated with the watchOS simulator. Use it to test the background functionality of your app." I have not seen any instructions or guides about how to do this. Therefore, I am wondering how I can simulate Fall Detection events in the WatchOS Simulator? Thank you so much!
Asked
by dandahar.
Last updated
.
Post not yet marked as solved
160 Views

CMSensorRecorder and WCSession

I am recording accelerometer data using CMSensorRecorder and then trying to retrieve the data in background refresh. However, I am getting the following error: "[Connection] Error on message reply (sync) for kCLConnectionMessageSensorRecorderGetMetasByDateRange (Connection interrupted)" Thanks in advance.
Asked
by Mru-Son.
Last updated
.
Post not yet marked as solved
503 Views

WatchOS Fall Detection

I am trying to use the Fall Detection API to handle fall event, but I keep getting : [Fall] Error fetching most recent fall event: 111 I am using CMFallDetectionManager with delegate The call back like the one below is not happening, any idea why? How to simulate fall using the Watch Series 6 simulator? func fallDetectionManager(_ fallDetectionManager: CMFallDetectionManager, didDetect event: CMFallDetectionEvent, completionHandler handler: @escaping () - Void) {     logger.debug("Fall Event Detected") }
Asked
by dkam.
Last updated
.
Post not yet marked as solved
178 Views

User Activity Recognition

Hi Team, help me out to know,, is it possible to get user activity status , even when app is TERMINATED or SUSPENDED. NOTE: as of now, i can track user activity , when app is in background i want to get activity , even when app is TERMINATED BY USER. thanks in advance, help me out.
Asked Last updated
.
Post not yet marked as solved
166 Views

Activity Recognition

I want to detect activity and get location,, only when user enter his/her vehicle
Asked Last updated
.
Post not yet marked as solved
210 Views

Directly access to hand gestures like clench.. ? (Interface)

Hey everyone, I have a question about hand gestures. Does an app only have access to hand gestures when assistivetouch is activated? Or is there an interface in the documentation, which gives you directly access to the recognition of these hand gestures? Example: Thinking of a game that will be played with hand gestures. The character jumps when the user does a clench and stops when the user clenched twice. Would that be possible or works it only if the assistivetouch is activated and configured?
Asked
by Bendo.
Last updated
.
Post not yet marked as solved
194 Views

CoreMotion CLClientCreateIso6709Notation Crash

I'm writing to see if anyone can help me debug a common crash I see in my crash reports. Context: My app uses CoreLocation for location tracking and also ARKit. These are both used only while the user is 3D scanning, and otherwise they are not used. We see the crash happening randomly when the user is in 3D scanning mode, also when they are not (when CoreLocation and CoreMotion should not be used at all). This is the most common crash we see in Crashlytics, but there is no reliably way to reproduce and as far as we can tell we are using the frameworks correctly. Does anybody know what's going on or have any suggestions to help debug? Much appreciated Stack trace: 0 CoreMotion 0x1b5aa4774 CLClientCreateIso6709Notation + 190724 1 CoreMotion 0x1b5a9f69c CLClientCreateIso6709Notation + 170028 2 CoreMotion 0x1b5b4680c CLShouldDisplayEEDUI + 271016 3 IOKit 0x1b5864958 __IOHIDEventSystemClientQueueCallback + 288 4 CoreFoundation 0x1aa90ba5c __CFMachPortPerform + 176 5 CoreFoundation 0x1aa931274 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 60 6 CoreFoundation 0x1aa9305f4 __CFRunLoopDoSource1 + 596 7 CoreFoundation 0x1aa92a1d8 __CFRunLoopRun + 2372 8 CoreFoundation 0x1aa929360 CFRunLoopRunSpecific + 600 9 CoreFoundation 0x1aa92a44c CFRunLoopRun + 64 10 CoreMotion 0x1b5aa5c78 CLClientCreateIso6709Notation + 196104 11 libsystem_pthread.dylib 0x1f6630bfc _pthread_start + 320 12 libsystem_pthread.dylib 0x1f6639758 thread_start + 8
Asked Last updated
.