Core Motion

RSS for tag

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

Core Motion Documentation

Posts under Core Motion tag

33 Posts
Sort by:
Post marked as solved
2 Replies
693 Views
hi there, one thing i'm working on for the vision pro requires knowing the user's heading relative to north (magnetic or true). basically it's working with objects located using geo coordinates, and getting an angle of the direction the user is facing relative to them. on iOS and watchOS, i can use CMMotionManager's CMDeviceMotion heading property. looking at the docs it says this heading is there for visionOS, as is the xMagneticNorthZVertical reference frame.. however it seems like there is no magnetometer? it's a bit hard to tell in the simulator since isDeviceMotionAvailable, isAccelerometerAvailable and isGyroAvailable all return false. while isMagnetometerAvailable is a compile error (unavailable in visionOS). is there - or will there be - a way i can get the user's heading relative to north?
Posted
by ziggmike.
Last updated
.
Post not yet marked as solved
0 Replies
360 Views
Hi, is it possible to use CMHeadphoneMotionManager from WatchOS app? I'm trying to read accelerometer data of my AirPods Pro from WatchOS app. But I'm not receiving any updates and isDeviceMotionAvailable property is false. When I'm running the same code on iOS everything works fine.
Posted
by RomTok.
Last updated
.
Post not yet marked as solved
2 Replies
507 Views
Following the information of accessing the Submerged and Depth and Pressure data (https://developer.apple.com/documentation/coremotion/accessing_submersion_data), I would like to get the Submerged Depth and Pressure entitlement. I went to Certificates, Identifiers & Profiles (https://developer.apple.com/account/resources/identifiers/list) I created an Identifire of Apple ID, Select App, the Capabilitiy of 'Shallow Depth and Pressure' turned true, put my app's bundle ID I created an Profile, select the Identifire I made ealier which have the Capability of 'Shallow Depth and Pressure' I went back to X-code, applied the profile I made earlier I woudl like to know whether I need to add the capability of 'Shallow Depth and Pressure' on X-code. I looked for the menu to add Capabillity on the X-code 'Signing & Capabiities' tab and '+ Capability' nemu, but 'Shallow Depth and Pressure' is not on the lists. If anyone could share your info to get Submerged Depth and Pressure entitlement successrully on X-code, it would be appreciated.
Posted Last updated
.
Post not yet marked as solved
0 Replies
394 Views
Hello friends I’m currently developing an iOS application that uses the attitude from CoreMotion. For this I need to evaluate the specific values of Pitch, Roll and Yaw. As long as the app is in landscape mode and the device upright (X-axis up), I only need some small adjustments of the values to get the right attitude data. New: Pitch -> Y-axis, Yaw -> X-axis and Roll = Z-axis. func startDeviceMotion() { if motionManager.isAccelerometerAvailable { self.motionManager.deviceMotionUpdateInterval = self.interval self.motionManager.showsDeviceMovementDisplay = true self.motionManager.startDeviceMotionUpdates(using: .xTrueNorthZVertical) // Configure a timer to fetch the motion data self.timer = Timer(fire: Date(), interval: self.interval, repeats: true, block: { (timer) in if let motion = self.motionManager.deviceMotion { // write the values my own orientation data structure self.orientation.azimuthAngle = Measurement(value: -motion.attitude.yaw, unit: UnitAngle.radians) self.orientation.inclinationAngle = Measurement(value: -motion.attitude.roll-(Double.pi/2.0), unit: UnitAngle.radians) self.orientation.bankAngle = Measurement(value: motion.attitude.pitch, unit: UnitAngle.radians) } }) // Add the timer to the current run loop. RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.default) } } However, when I use it in portrait mode (Y-axis up), I can't find a suitable conversion that provides me good values. Most of the time I get mixed values. The goal is that the following axes define Pitch, Roll and Yaw. Pitch -> X-axis, Yaw -> Y-axis, Roll -> Z-axis Has anyone ever had this problem and could explain how to get meaningful pitch, roll and yaw values with an iPad in portrait mode? Kind regards
Posted Last updated
.
Post not yet marked as solved
2 Replies
832 Views
I recently updated my iPhone to iOS 17.0 (21A5248v) and my Apple Watch Series 8 to watchOS 10.0 (21R5275t). I'm working with the CMBatchedSensorManager and have confirmed that the authorizationStatus is authorized. Additionally, both isDeviceMotionSupported and isAccelerometerSupported properties return true. However, when I call the startAccelerometerFetching() function shown below: @available(watchOS 10.0, *) func startAccelerometerFetching() async { do { for try await accelerometerList in batchedSensorManager.accelerometerUpdates() { accelerometerList.forEach { self.processAccelerometer($0) } } } catch let error as NSError { print("Encountered Error: \(error.userInfo) \(error.localizedDescription) -> \(error.code) \(error.localizedFailureReason)") } } I receive the following error message: "Encountered Error: [:] The operation couldn’t be completed. (CMErrorDomain error 109.) -> 109 nil" Does error code 109 correspond to CMErrorNotAvailable? How to solve this problem?
Posted Last updated
.
Post not yet marked as solved
2 Replies
1.1k Views
Our App has a feature that needs to determine if the phone was stationary during the last 10 seconds. For the past several years, we have been using CMMotionActivityManager for this feature and it has worked very reliably. We query motion activity for the past 10 seconds (using queryActivityStarting(from:to:to:) method) and check for any events where the stationary property is false. However, the behavior of CMMotionActivityManager has changed in iOS 16.4 Beta: CMMotionActivityManager no longer reports motion as it did on iOS 16.3 and earlier versions. With iOS 16.4 Beta, CMMotionActivityManager will falsely return events where the stationary property is true (or return no events) even though the phone was in motion during the query interval. There are times when it does return motion events correctly, but that only happens if the phone is in constant motion for a sustained period of time. This behavior is drastically different from previous iOS versions where even the slightest bit of movement would generate motion events. i'm really hoping this is an issue in the beta and will be sorted out soon. Feedback Filed: FB12005598
Posted
by nokey4.
Last updated
.
Post not yet marked as solved
1 Replies
406 Views
Hello, I am working on a clinical-grade application with access to the CMMovementDisorderManager API to track Parkinson's symptoms. Sometimes, these two method calls produce an NSError in the CMErrorDomain with code 103, which appears to be CMErrorUnknown: [CMMovementDisorderManager queryDyskineticSymptomFromDate:toDate:withHandler:] [CMMovementDisorderManager queryTremorFromDate:toDate:withHandler:] This is difficult for us to track down, because the error code is nondescript, and the user info is empty. We really don't have any clues as to what could be causing this behavior. I'm hoping a CoreMotion framework engineer with visibility into the code may be able to take a look and let us know what conditions can cause this result. Thanks! Dan
Posted
by damato.
Last updated
.
Post not yet marked as solved
6 Replies
2.2k Views
Hi, I have a core ml model that when I try to print the: modelPrediction?.labelProbability which is of type String:Double and contains all the features with their corresponding probabilities, the value of type double comes with nan rest = nan right = nan up = nan Sometimes restarting makes it work again. Sometimes it can take a lot of restarts to start working again. Even when deleting the app and installing again the same thing happens. Also tried changing the deployment version but didn't seem to fix it. Any help is appreciated.
Posted
by jessylol.
Last updated
.
Post not yet marked as solved
0 Replies
552 Views
"for try await dataArray in bsm.deviceMotionUpdates()" generate error: Error Domain=CMErrorDomain Code=109 "(null)" Environment iOS 17.0 (21A5277j) watchOS 10.0 (21R5295g) XCode 15.0 beta 4 (15A5195m) Mac Studio 2022, macOS 13.4.1 (22F82) Details I create a swift project with code: File 1: let healthStore = HKHealthStore() var workoutSession: HKWorkoutSession! func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) { } func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) { } func requestAuthorization() { // The quantity type to write to the health store. let typesToShare: Set = [ HKQuantityType.workoutType() ] // The quantity types to read from the health store. let typesToRead: Set = [ HKQuantityType.quantityType(forIdentifier: .heartRate)!, HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)!, HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning)! ] // Request authorization for those quantity types healthStore.requestAuthorization(toShare: typesToShare, read: typesToRead) { success, error in // Handle error. } } // before call startWatch(), will request authorization to access Healthkit func startWatch(_ startWatchFor:Int) -> MotionManager? { let configuration = HKWorkoutConfiguration() let motionMgr: MotionManager? configuration.activityType = .golf configuration.locationType = .outdoor do { workoutSession = try HKWorkoutSession(healthStore: healthStore, configuration: configuration) workoutSession.startActivity(with: Date()) } catch { // Handle any exceptions. return nil } workoutSession.delegate = self ... // in turn, a func startUpdates() in another swift file will be called. } File 2: var batchedSensorManager: Any? @available(watchOSApplicationExtension 6.0.0, *) func batchedSensorUpdates() async { if #available(watchOSApplicationExtension 10.0, *), let bsm = batchedSensorManager as? CMBatchedSensorManager { bsm.startDeviceMotionUpdates() do { for try await dataArray in bsm.deviceMotionUpdates() { if !processDMEntry { break } ... // process data } } catch let error as NSError { print("batchedSensorManager.deviceMotionUpdates() fail", error.description) } } }
Posted
by ATMooee.
Last updated
.
Post not yet marked as solved
0 Replies
612 Views
Good day, Fist I have to be honest. I was not developing for iOS for years, while I wanted to get back to if for quite some time. I started looking into CMWaterSubmresionManager documentation and I simply couldn't make it work. Then I got back to iOS basics to refresh my knowledge. I remembered and learned quite a few things, but still after hours and hours of trying and following various similar other Manager use. I still am not able to make any sense how to get CMWaterSubmresionManager delegate to work. My goal is very very simple - new Xcode project for watchOS app, witch companion app, which would allow me to capture info like water temperature, time underwater etc. I went through the documentation and did set all the prerequisites, like added authorisation for motion data, extended runtime session etc as per documentation: https://developer.apple.com/documentation/coremotion/accessing_submersion_data funny enough tried to start monitoring for data in the view. Obviously could set submersionManager.delegate = self, as it "Cannot find 'self' in scope;". Created a class, but could not call it (sorry can't remember the error already) and finally went through "Build a workout app for Apple Watch" ( https://developer.apple.com/wwdc21/10009 ) trying to setup CMWaterSubmerionManager similarly to WorkoutManager and got stuck on on EnviromentalObject Observable something error, which likely does not make any difference, because no such was mentioned anywhere in CMWaterSubmersionManager documentation. I tried to revert from Enviroment object but eventually getting "Constant 'submersionManager' captured by a closure before being initialized", which makes me thing I messed up in so many ways, I cant even track back. I am totally stuck and can't find any info anywhere on internet, no samples, nothing anywhere. If anyone could help making it work, I would be very grateful. My SumbersionManager file looks like: import CoreMotion import WatchKit class SubmersionManager: NSObject, CMWaterSubmersionManagerDelegate, WKExtendedRuntimeSessionDelegate { func extendedRuntimeSession(_ extendedRuntimeSession: WKExtendedRuntimeSession, didInvalidateWith reason: WKExtendedRuntimeSessionInvalidationReason, error: Error?) { print("extended session did error") } func extendedRuntimeSessionDidStart(_ extendedRuntimeSession: WKExtendedRuntimeSession) { print("extended session did START") } func extendedRuntimeSessionWillExpire(_ extendedRuntimeSession: WKExtendedRuntimeSession) { print("extended session did EXPIRE") } func manager(_ manager: CMWaterSubmersionManager, didUpdate event: CMWaterSubmersionEvent) { print("didSubmerge??") } func manager(_ manager: CMWaterSubmersionManager, didUpdate measurement: CMWaterSubmersionMeasurement) { print("someMeasurement") } func manager(_ manager: CMWaterSubmersionManager, didUpdate measurement: CMWaterTemperature) { print("some temperature") } func manager(_ manager: CMWaterSubmersionManager, errorOccurred error: Error) { print("some error") } func testSinc () { guard CMWaterSubmersionManager.waterSubmersionAvailable else { return } // Instantiate the submersion manager. let submersionManager = CMWaterSubmersionManager() // Assign the submersion manager delegate. submersionManager.delegate = self } func myStartDiveSession() { // logger.info("*** Starting a dive session. ***") print("*** Starting a dive session. ***") // Create the extended runtime session. let session = WKExtendedRuntimeSession() // Assign a delegate to the session. session.delegate = self // Start the session. session.start() } } nonisolated func manager(_ manager: CMWaterSubmersionManager, didUpdate event: CMWaterSubmersionEvent) { let submerged: Bool? switch event.state { case .unknown: submerged = nil case .notSubmerged: submerged = false case .submerged: print("submerged!!!!!!!!!") submerged = true @unknown default: } Task { if let submerged { print("submerged!!!!") } } } // Respond to errors. nonisolated func manager(_ manager: CMWaterSubmersionManager, errorOccurred error: Error) { } And I am simply trying to call it from view by initializing let submersionManager : SubmersionManager and .onAppear() { print("appeared in view") submersionManager.myStartDiveSession() OR submersionManager.testSync() "and getting mentioned captured by a closure before being initialized" error
Posted
by wza180.
Last updated
.
Post not yet marked as solved
1 Replies
714 Views
I would like to offer some suggestions to enhance the user experience on iOS devices. Recently, I have noticed that some applications utilize the gyroscope sensor to trigger ad browsing or other actions. However, this feature can lead to accidental activations, causing inconvenience for users. I would like to propose the addition of a feature in future iOS versions that allows users to control the usage of the gyroscope sensor. This way, users can decide whether to grant access to the gyroscope sensor for applications based on their preferences. Such a control option would empower users to better manage the behavior of their devices and applications, resulting in an improved user experience and satisfaction. By providing users with the ability to control gyroscope sensor permissions, you would offer greater flexibility and autonomy, while reducing the risk of accidental activations. This would be a significant enhancement for users who wish to avoid triggering ads or other actions due to unintentional device movements. I firmly believe that as a leading technology company, you are committed to delivering exceptional user experiences. By incorporating control options for the gyroscope sensor, you would further strengthen user trust and satisfaction with the iOS ecosystem. Thank you for your time and consideration of this suggestion. I look forward to future advancements from your team that will make iOS one of the most delightful and highly customizable mobile operating systems. Best regards By the way, the creators of this way of advertising won an award for it. I wanna say shameless hooligans i **** 'em
Posted Last updated
.
Post not yet marked as solved
4 Replies
3k Views
I want to record both IMU data and Audio data from Airpods Pro. I have tried many times, and I failed. I can successfully record the IMU data and iPhone's microphone data simultaneously. When I choose Airpods Pro's microphone in the setCategory() function, the IMU data collection process stopped. If I change recordingSession.setCategory(.playAndRecord, mode: .default, options: .allowBluetooth) to ecordingSession.setCategory(.playAndRecord, mode: .default), everything is okay except the audio is recorded from the handphone. If I add options: .allowBluetooth, the IMU update will stop. Could you give me some suggestions for this? Below are some parts of my code.   let My_IMU = CMHeadphoneMotionManager()   let My_writer = CSVWriter()   var write_state: Bool = false   func test()   {     recordingSession = AVAudioSession.sharedInstance()     do {       try recordingSession.setCategory(.playAndRecord, mode: .default, options: .allowBluetooth)       try recordingSession.setActive(true)       recordingSession.requestRecordPermission() { [unowned self] allowed in         DispatchQueue.main.async {           if allowed == false {print("failed to record!")}         }       }     } catch {       print("failed to record!")     }                 let audioFilename = getDocumentsDirectory().appendingPathComponent("test_motion_Audio.m4a")     let settings = [       AVFormatIDKey: Int(kAudioFormatMPEG4AAC),       AVSampleRateKey: 8000,       AVNumberOfChannelsKey: 1,       AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue     ]     do     {       audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)       audioRecorder.delegate = self       audioRecorder.record()     }     catch     {       print("Fail to record!")       finishRecording()     }           write_state.toggle()     let dir = FileManager.default.urls(      for: .documentDirectory,      in: .userDomainMask     ).first!           let filename = "test_motion_Audio.csv"     let fileUrl = dir.appendingPathComponent(filename)     My_writer.open(fileUrl)           APP.startDeviceMotionUpdates(to: OperationQueue.current!, withHandler: {[weak self] motion, error in       guard let motion = motion, error == nil else { return }       self?.My_writer.write(motion)     })   }
Posted
by wang0665.
Last updated
.