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 not yet marked as solved
0 Replies
63 Views
how could I remove the key NSMotionUsageDescription? cause it leads some crash problem.But after I remove the key NSMotionUsageDescription, I submit to Apple Store connect,I will receive issue .TMS-90683: Missing purpose string in Info.plist - Your app’s code references one or more APIs that access sensitive user data, or the app has one or more entitlements that permit such access. The Info.plist file for the “ydbus.app” bundle should contain a NSMotionUsageDescription key with a user-facing purpose string explaining clearly and completely why your app needs the data. If you’re using external libraries or SDKs, they may reference APIs that require a purpose string. While your app might not use these APIs, a purpose string is still required. For details, visit: https://developer.apple.com/documentation/uikit/protecting_the_user_s_privacy/requesting_access_to_protected_resources. How could I solve the problem? I reviewed my project,I don't use the key NSMotionUsageDescription api.
Posted Last updated
.
Post not yet marked as solved
0 Replies
211 Views
I'm trying to use CMAcceleration data in my app to detect when the user is doing certain kinds of activities. The problem I'm having is that the acceleration data for the same user motions is different depending on how they are holding their phone. I don't care about the orientation of the phone, I just care about the overall motion of the person holding it. I've researched and tried a whole bunch of ways to correct the data for phone orientation, such as rotating the acceleration using the CMAttitude rotation matrix, removing the effect of gravity with a series of calculations, and doing both of these in both orders. I can't seem to come up with something that works. I think there has to be some solution since iOS can do things like step counting which I assume doesn't depend on the orientation of the phone. Thanks, Frank
Posted
by flarosa.
Last updated
.
Post not yet marked as solved
3 Replies
229 Views
I'm not getting any values from the floorsAscended or floorsDescended properties of CMPedometerData. I tested it by walking up and down a flight of stairs twice while monitoring for pedometer updates for 60 seconds. I also queried for the pedometer data separately at the end of the time period in case there were any updates I missed. I'm using an iPhone 13 pro for my tests and I did check to make sure CMPedometer.isFloorCountingAvailable() is true, and I am getting other kinds of pedometer data such as distance, pace, and steps. Is there something else I need to do in order to enable floor counting? Thanks, Frank
Posted
by flarosa.
Last updated
.
Post not yet marked as solved
1 Replies
268 Views
I'm working on a screen where the goal is for the user to walk for 6 minutes while the app times them and measures the distance walked. I'm using CMPedometer to track the walking distance and a repeating 1-second Timer to count down the time. This works fine as long as the app is in the foreground, but I'd like my user to be able to lock their phone and put it away while they walk. I used UIApplication.shared.beginBackgroundTask, but it doesn't provide enough time. It usually only gives me around 30 seconds. I also tried calling UIApplication.shared.beginBackgroundTask again or calling it once every time the timer ticks, with no better result. How can I accomplish my goal here?
Posted
by flarosa.
Last updated
.
Post not yet marked as solved
0 Replies
195 Views
I cannot get CMMotionActivityManager.startActivityUpdates() to work. I have given my app permission to use core motion and also put the required description key into my Info.plist file. I am expecting my user to walk. I call startActivityUpdates() and then stand up and start walking. I typically get about 3 callbacks within a couple of seconds, all of which have "false" set for all of the activity flags, even "unknown". Then after that I get nothing. I can't figure out what I could possibly be doing wrong here. The code is really simple. I looked at doezens of examples and my code is doing the exact same things.
Posted
by flarosa.
Last updated
.
Post not yet marked as solved
0 Replies
158 Views
I'm trying to create a productivity app that utilizes gyroscope data to detect when the phone is picked up. However, in my code, it seems that after I detect the phone flipping over, gyro updates become unavailable and I start receiving the sentinel value instead, which causes the code to not work properly. What happens is that I will receive gyro updates until faceUp changes value, at which point gyroData becomes unavailable. let dTheta = Double(self.manager.gyroData?.rotationRate.y ?? 0) if dTheta > 0.1 || dTheta < -0.1 { totalRotation = totalRotation + dTheta } tO = Date.now if(totalRotation >= 0.9 || totalRotation <= -0.9) { //Block that detects a phone flip if faceUp == true { faceUp = false } else if faceUp == false { faceUp = true stopText = "Timer paused at \(currentTimeRemaining)" } totalRotation = 0 } guard shouldProceed() else { return } currentTimeRemaining = dispTime(mustRedo: mustRedo) keepScreenOn() let hours = job.hours let mins = job.mins let secs = job.seconds if mins == 0 && hours == 0 { minsDone = true } if secs == 0 && mins == 0 { secsDone = true } if mins == 0 && minsDone == false { job.setHours(new: (hours-1)) job.setMins(new: 59) } if job.seconds == 0 && secsDone == false{ job.setMins(new: (mins-1)) job.setSeconds(new: 59) } if hours == 0 && minsDone == true && secsDone == true { workTimeActive = false //stopTimer() } else { job.setSeconds(new: job.seconds-1) } if manager.isGyroActive == false {print("not active tag 3")} currentTimeRemaining = dispTime(mustRedo: mustRedo) private func keepScreenOn() { UIApplication.shared.isIdleTimerDisabled = true } private func shouldProceed() -> Bool{ if faceUp == true { if manager.isGyroActive == false {print("not active tag 4")} return false } return true }
Posted Last updated
.
Post not yet marked as solved
0 Replies
249 Views
Hi all, I am trying to build an app which, on support Apple Watch's (currently just the Ultra's), will detect when the watch has been submerged and will start to report temperature from the sensor. I have followed the developer articles I could find around CMWaterSubmersionManager and have set up a simple class to interact with it. It is now that I want to run my app and test if it is working as I expect it to etc. However I noticed that the waterSubmersionAvailable is only set to true on physical Apple Watch Ultra and Ultra 2. This is rather inconvenient as it means that for the next week or so while developing this feature I will have to stick my arm wearing the watch into a container of water to test the feature. Just wondering if there is any easier way to debug this stuff that anyone has figured out? It would be ideal if this could just be done in the simulator similar to how other device conditions can be induced. I did notice the "Enable Easy Submersion" option in the Debug menu, however I could not figure out a difference between having this on or off, and could not find any explanation of what it actually does on the docs. Does anyone have any experience with this either? Any advice would be appreciated, and to any Apple engineers who may see this, please please please add an option to be able to debug this stuff in the Simulator
Posted
by devharry.
Last updated
.
Post not yet marked as solved
1 Replies
261 Views
Hello All, I am building an application that involves the usage of accelerometer data. How I handle the data will change based on the accelerometer specifications. I have been looking all over for the accelerometer specifications for the iPhone13 (the iPhone that I am testing my application on), but I cannot find it anywhere. Is it public knowledge?
Posted Last updated
.
Post not yet marked as solved
1 Replies
306 Views
Hey, everyone! I've been testing my .swiftpm app on an iPhone. If you're wondering about how I made the connections, I used a cable plugged into my Mac so that Xcode could communicate with the phone. Do you think that evaluators of the app will be alright with this method of testing it out as well? I'm particularly leaning towards the iPhone platform because my app requires a pedometer. Thanks! Ethan
Posted Last updated
.
Post not yet marked as solved
1 Replies
236 Views
I am currently developing app that counts the Steps, and for that I am using the pedometer. I am not sure of how frequent pedometer provides updates, in my case it provides update around 3 second. There is nothing mentioned about frequency of Data in Official documentation of Apple or Any ways to set the Frequency. Application is in Both iOS and WatchOS plateform To achieve data i have tried following things: With startUpdates(from: Date) pedometer.startUpdates(from: Date()) { [weak self] pedometerData, error in guard let data = pedometerData, error == nil else { return } DispatchQueue.main.async { self?.stepCount = data.numberOfSteps.intValue } } With queryPedometerData() timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in self?.fetchPedometerData() } private func fetchPedometerData() { pedometer.queryPedometerData(from: Date().addingTimeInterval(-1), to: Date()) { [weak self] pedometerData, error in guard let data = pedometerData, error == nil else { return } DispatchQueue.main.async { self?.stepCount = data.numberOfSteps.intValue } } } I have done this both implementation but Not getting desired results. I want data every second, Could it be possible ? Any help or leads would really helpful Thank You :)
Posted Last updated
.
Post not yet marked as solved
0 Replies
240 Views
I'm building a physical therapy app and as part of it, I want the app to oversee and measure certain exercises that the user will do. I'm not sure if I should use Core Motion, location services, or something else. These are the specific things we want to measure: The user walks for 6 minutes. At the end of it, we tell them how far they walked. The user runs for 30 seconds. We tell them their average speed and peak speed. The user does a broad jump: basically just jumping forward as far as they can. We want to measure the distance jumped. I'm thinking location services might work for #1 but I doubt it will be accurate enough for #2. For #3 I thought I could do this with the accelerometer if I took readings at short intervals and combined them with something like the trapezoidal rule, but I can't get this to produce a reliable result. Let me know what you think, thanks.
Posted
by flarosa.
Last updated
.
Post not yet marked as solved
0 Replies
240 Views
Starting at point zero. I want to calculate the position of the iphone. I've read and many people say this is not possible but this was in 2012 ish. I'm sure the sensors have imporved and this is possible now
Posted
by DeerBrain.
Last updated
.
Post not yet marked as solved
2 Replies
903 Views
Following https://developer.apple.com/documentation/coremotion/accessing_submersion_data I'm trying to "just get it started". I have a provisioning profile with the Shallow Depth and Pressure active, I have set the com.apple.developer.submerged-depth-and-pressure to true in the entitlements file, and get no errors or warning when compiling and starting the app on my Apple Watch Ultra. When my view appears, I init the submersion manager with the following code: guard CMWaterSubmersionManager.waterSubmersionAvailable else { return } submersionManager = CMWaterSubmersionManager() submersionManager?.delegate = self Logger.shared.info("SubmersionManager initialized") I get the printout SubmersionManager initialized, but then I get: An error occurred: The operation couldn’t be completed. (CMErrorDomain error 110.) Googling this error tells me this error means: CMErrorNotEntitled And I cannot find WHY the app is not entitled.. I find no information that this entitlement is not publicly available or anything.
Posted Last updated
.
Post not yet marked as solved
0 Replies
262 Views
Hello, When sometimes have bad values when reading the AbsoluteAltitude of the Watch. I'm running WatchOS 10.2 and it seems to be a new issue/bug. When I print out the debugDescription of the received data, I got a statusInfo field at 0 when it works, and at 2 when not. But I didn't find any explanation of the value nor how to access it. // OK: 0 Optional(AbsoluteAltitude: 223.266052, Accuracy: 6.944067, Precision 0.500000, statusInfo: 0, timestamp :726142069.230969) // NOT OK: 2 Optional(AbsoluteAltitude: 121.610824, Accuracy: 3.156758, Precision 5.000000, statusInfo: 2, timestamp :726152607.239057) Have someone experienced similar issues or now what this field is for? Thx and greetings!
Posted
by MyMacFTW.
Last updated
.
Post not yet marked as solved
7 Replies
652 Views
I have a swift callback function that accumulates data from the gyroscope handler CMGyroData to value, and takes care that it never goes below zero. Any thoughts why I got this crash? var value: Double = 90 func test(d: Double) { value -= d if value < 0 { value = 0 } else if value > 180 { value = 180 } // Double value cannot be converted to UInt8 because the result would be less than UInt8.min // according to Xcode, value is 0 let angle = UInt8(value.rounded()) print(angle) } During the crash, the debugger shows that value is 0, and the raw memory is 0x0000000000000000. I've heard about negative zero, but then the raw memory would be 0x8000000000000000. Either way, it makes no sense for the UInt8 constructor to fail. (lldb) p value (Double) 0 (lldb) p value.rounded() (Double) 0 (lldb) p UInt8(value.rounded()) (UInt8) 0 Xcode 15.1, iPhone 7 Plus, iOS 15.8 Edit: As a good measure, I changed that line to let angle = UInt8(Int(value.rounded()))
Posted
by gvalkov.
Last updated
.
Post not yet marked as solved
0 Replies
359 Views
Hello everyone, I'm coming to you because I'm having a little trouble finding the code to know the movement of the Apple Watch. I try to know exactly when the arm movement is up, down, left or right. I can define it thanks to “attitude.pitch” I can define it using "attitude", but it doesn't work correctly when the wrist is rotating at the same time as an arm movement. I no longer know how to move forward to know each movement. My code is as follows: (attitudeAvant11 is the attitude to the forward scan) (attitude11 is the attitude.pitch on the AppleWatch) Thank for your help func knowMove (attitude11:Double, attitudeAvant11:Double) -> (Sens2:String, attitudeAvant12:Double) { var attitude1 = attitude11 attitude1 = attitude1 * 100 let pourcentage = attitude1 - attitudeAvant if attitudeAvant != 0 { if pourcentage >= 0.5 { sensPrint = "Sens: Move down // ➡️\(pourcentage) ⬅️ // \(attitude1) // \(attitudeAvant)" sens1 = "1" } else { if pourcentage < -1.2 { sensPrint = "Sens: Move Up // ➡️\(pourcentage)⬅️ // \(attitude1) // \(attitudeAvant)" sens1 = "2" } else { sensPrint = "Sens: No Move // ➡️\(pourcentage)⬅️ // \(attitude1) // \(attitudeAvant)" sens1 = "0" } } } else { sensPrint = "Sens: No Move Initialisation // ➡️\(pourcentage)⬅️ // \(attitude1) // \(attitudeAvant) " } let DateMaintenant = Date() let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" let dateString = formatter.string(from: DateMaintenant) if sens1 != "Nul" { TableauAttitude["\(dateString)"] = "\(sens1)" //print(TableauAttitude) } attitudeAvant = attitude1 print("sensPrint: \(sensPrint)") return (sens1,attitudeAvant) }
Posted
by MaximeHae.
Last updated
.
Post marked as solved
2 Replies
614 Views
I wrote my app with the entitlement "com.apple.developer.submerged-shallow-depth-and-pressure" and also with underwater-depth for WKBackgroundMode. All is working fine when I tested the app. When I want to put the app in the store I got the following error: **Missing entitlement. The Info.plist for the watchOS app bundle at “Watch App.app” uses the underwater-depth value for WKBackgroundModes without the com.apple.developer.submerged-depth-and-pressure entitlement signed into the bundle. ** I wonder why the entitlement in the error message is without -shallow- and why I get this message.
Posted
by thom93055.
Last updated
.
Post not yet marked as solved
1 Replies
354 Views
I am writing a code to capture the accelerometer data for one hour, it suppose to save in the iOS device first, and then I would like to upload to cloudkit. Here is my code. import UIKit import CoreMotion import CloudKit class ViewController: UIViewController { @IBOutlet weak var accelerometerSwitch: UISwitch! private let recorder = CMSensorRecorder() private let cloudKitContainer = CKContainer(identifier: "iCloud.com.example.accelerometer-recorder") override func viewDidLoad() { super.viewDidLoad() accelerometerSwitch.addTarget(self, action: #selector(accelerometerSwitchValueChanged), for: .valueChanged) } private func saveDataToAppFolder(data: [CMSensorRecordingData]) { let fileName = "accelerometer_data.dat" let fileManager = FileManager.default let documentsDirectoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! let fileURL = documentsDirectoryURL.appendingPathComponent(fileName) let jsonData = try! JSONEncoder().encode(data) try! jsonData.write(to: fileURL) } @objc private func accelerometerSwitchValueChanged() { if accelerometerSwitch.isOn { recorder.recordAccelerometer(forDuration: 3600.0) { sensorData in if let sensorData = sensorData { // Handle the recorded data saveDataToAppFolder(data: sensorData) uploadDataToCloudKit(data: sensorData) } else { print("No accelerometer data recorded") } } } else { // No need to stop recording since it will stop automatically after the duration } } private func uploadDataToCloudKit(filePath: String) { let fileURL = URL(fileURLWithPath: filePath) let data = try! Data(contentsOf: fileURL) let record = CKRecord(recordType: "RecordedData") record["data"] = data let database = cloudKitContainer.publicCloudDatabase database.save(record, completionHandler: { record, error in if let error = error { print("Error uploading data to CloudKit: \(error)") } else { print("Data uploaded to CloudKit successfully") } }) } } Anyone can help to fix the error. Thanks a lot.
Posted
by douglasng.
Last updated
.
Post not yet marked as solved
1 Replies
1.2k Views
I was following the below documentation for getting the Raw Gyroscope events. Somehow I am unable to make the below code working. if motion.isGyroAvailable { self.motion.gyroUpdateInterval = 1.0 / 60.0 self.motion.startGyroUpdates() // Configure a timer to fetch the accelerometer data. self.acceTimer = Timer(fire: Date(), interval: (1.0/60.0), repeats: true, block: { (timer) in // Get the gyro data. if let data = self.motion.gyroData { let x = data.rotationRate.x let y = data.rotationRate.y let z = data.rotationRate.z // Use the gyroscope data in your app. print("rotationX: \(x) , rotationY: \(y) , rotationZ: \(z)") } }) // Add the timer to the current run loop. RunLoop.current.add(self.acceTimer!, forMode: .default) } https://developer.apple.com/documentation/coremotion/getting_raw_gyroscope_events The isGyroAvailable always returns false Dev environment - Xcode 14.1, Apple Watch 8, WatchOS 9.1
Posted Last updated
.
Post not yet marked as solved
1 Replies
916 Views
I recently stumbled upon a peculiar issue that's causing automatic reboots on the iPhone 15 Pro and iPhone 15 Pro Max. It appears that setting an extremely high value for gyroUpdateInterval can lead to this problem, but interestingly, the iPhone 15 doesn't exhibit the same behavior. Here's the code in question: - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { self.motionManager = CMMotionManager.new; self.motionManager.gyroUpdateInterval = 3600; // The problematic line [self.motionManager startGyroUpdatesToQueue:NSOperationQueue.mainQueue withHandler:^(CMGyroData * _Nullable gyroData, NSError * _Nullable error) { NSLog(@"Gyroscope data: %@", gyroData); }]; } It's worth noting that when I set gyroUpdateInterval to a more reasonable value like 60 (or omit it, as it uses a default value in that case), the reboots don't occur on the affected devices. I have tested this behavior on both the iPhone 15 Pro and the iPhone 15 Pro Max, and the issue is consistent on both devices. Surprisingly, the iPhone 15 does not seem to experience this problem. I'm eager to hear from other developers who might have encountered this issue or have insights into why setting an extreme gyroUpdateInterval could result in device instability on the iPhone 15 Pro and iPhone 15 Pro Max. This might be a device-specific quirk or potentially a bug in the Core Motion framework.
Posted
by chengcong.
Last updated
.