Created
October 23, 2017 08:04
-
-
Save fitomad/a68ef8b04bce399b84032aea8eee1e19 to your computer and use it in GitHub Desktop.
Detect when your iPhone or iPad is near a magnet or ferrous material
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CoreMotion | |
import Foundation | |
let queue: OperationQueue = OperationQueue() | |
queue.qualityOfService = .utility | |
let motionManager: CMMotionManager = CMMotionManager() | |
motionManager.magnetometerUpdateInterval = 0.5 | |
motionManager.startMagnetometerUpdates(to: queue, withHandler: { (data: CMMagnetometerData?, error: Error?) -> Void in | |
guard let data = data else | |
{ | |
if let error = error | |
{ | |
print("err @ \(#function): \(error.localizedString)") | |
} | |
return | |
} | |
// Values units: Microteslas | |
print("Magnetic Field. x: \(data.magneticField.x), y: \(data.magneticField.y), z: \(data.magneticField.z)") | |
let average: Double = (data.magneticField.x + data.magneticField.y + data.magneticField.z) / 3.0 | |
print("Average: \(average)") | |
}) | |
// Don't forget to stop magnetometer updates | |
// when you don't need it anymore... | |
// motionManager.stopMagnetometerUpdates() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment