Get the data from Accelerometer, Gyroscope and Magnetometer in only Two or a few lines of code.

Related tags

Hardware MotionKit
Overview

#[MotionKit] (http://goo.gl/bpXBlO) — The missing iOS wrapper 🎶

Language Carthage compatible Version License Issues Join the chat at https://gitter.im/MHaroonBaig/MotionKit

Now you can grab the data from Accelerometer, Magnetometer, Gyroscope and Device Motion in a magical way, with just a Two or a few lines of code. Fully compatible with both Swift and Objective-C.

A nice and clean wrapper around the CoreMotion Framework written entirely in Swift. The Core Motion framework lets your application receive motion data from device hardware and process that data. The data can be retrieved from Accelerometer, Gyroscope and Magnetometer. You can also get the refined and processed gyroscope and accelerometer data from the deviceMotion datatype itself instead of getting the raw values.

Articles accompanying MotionKit: Link1Link2Link3 #How does it work You can retrieve all the values either by a trailing closure or by a delegate method. Both the approaches are fully supported.

Note: All the provided methods are Asynchronous and operate in their own Queue so that your app could run smoothly and efficiently.

##Initialise First, initialise the MotionKit instance. Its a Must.

Swift
```swift let motionKit = MotionKit() ```
Objective-C
```objective-c MotionKit *motionKit = [[NSClassFromString(@"MotionKit") alloc] init]; ```

##Getting Accelerometer Values You can get the accelerometer values using just a few lines of code.

Swift
```swift motionKit.getAccelerometerValues(interval: 1.0){ (x, y, z) in //Interval is in seconds. And now you have got the x, y and z values here .... } ```
Objective-C
```objective-c [motionKit getAccelerometerValuesWithInterval:1.0 values:^(double x, double y, double z) { // your values here }]; ```

##Getting Gyroscope Values Gyroscope values could be retrieved by the following few lines of code.

Swift
```swift motionKit.getGyroValues(interval: 1.0){ (x, y, z) in //Your processing will go here .... } ```
Objective-C
```objective-c [motionKit getGyroValues:1.0 values:^(double x, double y, double z) { // your values here }]; ```

##Getting Magnetometer Values Getting Magnetometer values is as easy as grabbing a cookie.

Swift
```swift motionKit.getMagnetometerValues(interval: 1.0){ (x, y, z) in //Do something with the retrieved values .... } ```
Objective-C
```objective-c [motionKit getMagnetometerValues:1.0 values:^(double x, double y, double z) { // your values here }]; ```

#Installation Embedded frameworks require a minimum deployment target of iOS 8. ###— Using CocoaPods Just add this to your Podfile.

pod 'MotionKit'

Note that you have to use CocoaPods version 0.36, the pre-released version which supports swift. If you don't already have it, you can grab it with a single command.

[sudo] gem install cocoapods --pre

###— Using Carthage You can use Carthage to install MotionKit by adding the following line to your Cartfile.

  github "MHaroonBaig/MotionKit"

###— Manual Installation Just copy the MotionKit.swift file into your Xcode project folder, and you're ready to go.

#CMDeviceMotion - as easy as pie In case if you want to get the processed values of Accelerometer or Gyroscope, you can access the deviceMotion object directly to get those values, or, you can access the individual values from the standalone methods which work seamlessly with Trailing Closures and Delegates.

The deviceMotion object includes:

  • Acceleration Data
    • userAcceleration
    • gravity
  • Calibrated Magnetic Field
    • magneticField
  • Attitude and Rotation Rate
    • attitude
    • rotationRate

All of the values can be retrieved either by individual methods or by getting the deviceMotion object itself.

###Getting the whole CMDeviceMotion Object

Swift
```swift
motionKit.getDeviceMotionObject(interval: 1.0){
    (deviceMotion) -> () in
      var accelerationX = deviceMotion.userAcceleration.x
      var gravityX = deviceMotion.gravity.x
      var rotationX = deviceMotion.rotationRate.x
      var magneticFieldX = deviceMotion.magneticField.x
      var attitideYaw = deviceMotion.attitude.yaw
      ....
    }
Objective-C
```objective-c [motionKit getDeviceMotionObjectWithInterval:1.0 values:^(CMDeviceMotion *deviceMotion) { // Your values here }]; ">


  
Objective-C
```objective-c [motionKit getDeviceMotionObjectWithInterval:1.0 values:^(CMDeviceMotion *deviceMotion) { // Your values here }];

###Getting refined values of Acceleration

You can get the refined and processed userAccelaration through the Device Motion service by just a few lines of code, either by a Trailing Closure or through Delegation method.

Swift
    motionKit.getAccelerationFromDeviceMotion(interval: 1.0){
        (x, y, z) -> () in
          // Grab the x, y and z values
          ....
        }
Objective-C
```objective-c [motionKit getAccelerationFromDeviceMotion:1.0 values:^(double x, double y, double z) { // your values here }]; ```

###Getting Gravitational Acceleration Again, you can access it through the Device Motion service as well.

Swift
```swift motionKit.getGravityAccelerationFromDeviceMotion(interval: 1.0) { (x, y, z) -> () in // x, y and z values are here .... } ```
Objective-C
```objective-c [motionKit getGravityAccelerationFromDeviceMotion:1.0 values:^(double x, double y, double z) { // your values here }]; ```

###Getting Magnetic Field around your device Interesting, Get it in a magical way.

Swift
```swift motionKit.getMagneticFieldFromDeviceMotion(interval: 1.0) { (x, y, z, accuracy) -> () in // Get the values with accuracy .... }
Objective-C
```objective-c [motionKit getMagneticFieldFromDeviceMotion:1.0 values:^(double x, double y, double z) { // your values here }]; ">


  
Objective-C
```objective-c [motionKit getMagneticFieldFromDeviceMotion:1.0 values:^(double x, double y, double z) { // your values here }];

###Getting the Attitude metrics

Swift
```swift motionKit.getAttitudeFromDeviceMotion(interval: 1.0) { (attitude) -> () in var roll = attitude.roll var pitch = attitude.pitch var yaw = attitude.yaw var rotationMatrix = attitude.rotationMatrix var quaternion = attitude.quaternion .... } ```
Objective-C
```objective-c [motionKit getAttitudeFromDeviceMotionWithInterval:1.0 values:^(CMAttitude *attitude) { // Your values here }]; ```

###Getting Rotation Rate of your device

Swift
```swift motionKit.getRotationRateFromDeviceMotion(interval: 1.0) { (x, y, z) -> () in // There you go, grab the x, y and z values .... }
Objective-C
```objective-c [motionKit getRotationRateFromDeviceMotion:1.0 values:^(double x, double y, double z) { // your values here }]; ">


  
Objective-C
```objective-c [motionKit getRotationRateFromDeviceMotion:1.0 values:^(double x, double y, double z) { // your values here }];

##Precautions For performance issues, it is suggested that you should use only one instance of CMMotionManager throughout the app. Make sure to stop receiving updates from the sensors as soon as you get your work done. You can do this in MotionKit like this.

    //Make sure to call the required function when you're done
    motionKit.stopAccelerometerUpdates()
    motionKit.stopGyroUpdates()
    motionKit.stopDeviceMotionUpdates()
    motionKit.stopmagnetometerUpdates()

##Delegates In case if you dont want to use the trailing closures, we've got you covered. MotionKit supports the following Delegate methods to retrieve the sensor values.

    optional func retrieveAccelerometerValues (x: Double, y:Double, z:Double, absoluteValue: Double)
    optional func retrieveGyroscopeValues     (x: Double, y:Double, z:Double, absoluteValue: Double)
    optional func retrieveDeviceMotionObject  (deviceMotion: CMDeviceMotion)
    optional func retrieveMagnetometerValues  (x: Double, y:Double, z:Double, absoluteValue: Double)


    optional func getAccelerationValFromDeviceMotion        (x: Double, y:Double, z:Double)
    optional func getGravityAccelerationValFromDeviceMotion (x: Double, y:Double, z:Double)
    optional func getRotationRateFromDeviceMotion           (x: Double, y:Double, z:Double)
    optional func getMagneticFieldFromDeviceMotion          (x: Double, y:Double, z:Double)
    optional func getAttitudeFromDeviceMotion               (attitude: CMAttitude)

To use the above delegate methods, you have to add the MotionKit delegate to your ViewController.

    class ViewController: UIViewController, MotionKitDelegate {
      ...
    }

And in the ViewDidLoad method, you simply have to add this.

    override func viewDidLoad() {
        super.viewDidLoad()
        motionKit.delegate = self
        ......
      }

Having that done, you'd probably want to implement a delegate method like this.

    func retrieveAccelerometerValues (x: Double, y:Double, z:Double, absoluteValue: Double){
      //Do whatever you want with the x, y and z values. The absolute value is calculated through vector mathematics
      ......
    }

   func retrieveGyroscopeValues (x: Double, y:Double, z:Double, absoluteValue: Double){
    //Do whatever you want with the x, y and z values. The absolute value is calculated through vector mathematics
    ......
   }

##Getting just a single value at an instant if you want to get just a single value of any of the available sensors at a given time, you could probably use some of the our handy methods provided in MotionKit.

###Accelerometer

Swift
```swift motionKit.getAccelerationAtCurrentInstant { (x, y, z) -> () in .... } ```
Objective-C
```objective-c [motionKit getAccelerationAtCurrentInstant:1.0 values:^(double x, double y, double z) { // your values here }]; ```

###Gravitational Acceleration

Swift
```swift motionKit.getAccelerationAtCurrentInstant { (x, y, z) -> () in .... } ```
Objective-C
```objective-c [motionKit getAccelerationAtCurrentInstant:1.0 values:^(double x, double y, double z) { // your values here }]; ```

###Attitude

Swift
```swift motionKit.getAttitudeAtCurrentInstant { (x, y, z) -> () in .... } ```
Objective-C
```objective-c [motionKit getAttitudeAtCurrentInstant:1.0 values:^(double x, double y, double z) { // your values here }]; ```

###Magnetic Field

Swift
```swift motionKit.getMageticFieldAtCurrentInstant { (x, y, z) -> () in .... } ```
Objective-C
```objective-c [motionKit getMageticFieldAtCurrentInstant:1.0 values:^(double x, double y, double z) { // your values here }]; ```

###Gyroscope Values

Swift
```swift motionKit.getGyroValuesAtCurrentInstant { (x, y, z) -> () in .... } ```
Objective-C
```objective-c [motionKit getGyroValuesAtCurrentInstant:1.0 values:^(double x, double y, double z) { // your values here }]; ```

#Discussion

#Requirements

  • iOS 7.0+
  • Xcode 6.1

#TODO

  • Add More Methods
  • Adding Background Functionality

#License Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

Comments
  • Objective C bridge

    Objective C bridge

    When including

    import "(mymodel)-swift.h"

    the generated header includes just the delegate methods.

    Adding the @objc in front of the swift methods doesn't work as it interferes with public

    could you provide an Objective C sample (I know you´ve written a lot in the realm but I can't instantiate the object ;-)

    opened by Tintenklecks 5
  • Objective-C Support

    Objective-C Support

    Swift use is not available in all scenarios (such as tweak development, which is what I do), not to mention some people simply prefer Objective-C to Swift. I think this project could benefit from having ObjC support.

    opened by codyd51 5
  • Update README.md

    Update README.md

    Fixed indentation and spacing inconsistencies. There are still many left, but I don't have time to correct them. The sloppiness of the README file also raises some question marks about the whole project for me too.

    opened by revolter 1
  • UI to start and stop recording?

    UI to start and stop recording?

    Could I ask you to add UI to start, stop and then display a kind of rolling buffer, similar to this but for audio:

    https://github.com/syedhali/EZAudio

    opened by scheung38 1
  • Delegate functions are not getting called

    Delegate functions are not getting called

    I have done like below in my ViewController

    `import UIKit
     import AVFoundation
     import CoreMotion
    
    class ViewController: UIViewController, MotionKitDelegate  {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let motionKit = MotionKit()
        motionKit.delegate = self
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func retrieveAccelerometerValues (x: Double, y:Double, z:Double, absoluteValue: Double){
    
    }
    
    func retrieveGyroscopeValues     (x: Double, y:Double, z:Double, absoluteValue: Double){
    
    }
    
    @objc func retrieveDeviceMotionObject  (deviceMotion: CMDeviceMotion){
    
    }
    
    
    func retrieveMagnetometerValues  (x: Double, y:Double, z:Double, absoluteValue: Double){
    
        print("x \(x), y \(y), z \(z), absoluteValue \(absoluteValue)")
    
    }
    
    func getAccelerationValFromDeviceMotion        (x: Double, y:Double, z:Double){
    
    
    }
    func getGravityAccelerationValFromDeviceMotion (x: Double, y:Double, z:Double){
    
    }
    
    func getRotationRateFromDeviceMotion           (x: Double, y:Double, z:Double){
    
        print("x \(x), y \(y), z(z)")
    
    }
    func getMagneticFieldFromDeviceMotion          (x: Double, y:Double, z:Double){
    
        print("x \(x), y \(y), z(z)")
    
    }
    
    @objc func getAttitudeFromDeviceMotion               (attitude: CMAttitude){
    
    }
    
    
    }
    

    ` I just see the only Log is MotionKit has been initialised successfully

    as you have done in the init() like below

     `   init(){
         NSLog("MotionKit has been initialised successfully")
       }   `
    

    I have changed like this

    `    init(){
        manager.showsDeviceMovementDisplay = true
        NSLog("MotionKit has been initialised successfully")
         }`
    

    still no any functions are called. What I am missing?

    opened by qadirsuh 0
  • Add a Gitter chat badge to README.md

    Add a Gitter chat badge to README.md

    MHaroonBaig/MotionKit now has a Chat Room on Gitter

    @MHaroonBaig has just created a chat room. You can visit it here: https://gitter.im/MHaroonBaig/MotionKit.

    This pull-request adds this badge to your README.md:

    Gitter

    If my aim is a little off, please let me know.

    Happy chatting.

    PS: Click here if you would prefer not to receive automatic pull-requests from Gitter in future.

    opened by gitter-badger 0
  • Updating framework to newer Swift syntax

    Updating framework to newer Swift syntax

    Hello; awesome project!

    This pull-request contains some updates to the Framework project that should enable to it be used with current (Swift-3) projects.

    It does not contain any updates to the example projects.

    Hope this is helpful! Nick

    opened by narner 2
  • Can't use this pod file with swift 2.2 and xcode 7.3.1

    Can't use this pod file with swift 2.2 and xcode 7.3.1

    # Uncomment the next line to define a global platform for your project
    # platform :ios, '9.0'
    
    target 'Sensor' do
      # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
      use_frameworks!
    pod 'MotionKit', :git => '[email protected]:MHaroonBaig/MotionKit.git'
      # Pods for Sensor
    
    end
    
    opened by Istiakmorsalin 0
  • XCode 8

    XCode 8

    I'm unable to build this with Carthage and XCode 8. I get the following error from the compiler:

    Build settings from command line: BITCODE_GENERATION_MODE = bitcode CARTHAGE = YES CODE_SIGN_IDENTITY = CODE_SIGNING_REQUIRED = NO ONLY_ACTIVE_ARCH = NO SDKROOT = iphoneos10.1

    === CLEAN TARGET MotionKit OF PROJECT MotionKit WITH CONFIGURATION Release ===

    Check dependencies “Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly. “Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

    ** CLEAN FAILED **

    The following build commands failed: Check dependencies (1 failure) === BUILD TARGET MotionKit OF PROJECT MotionKit WITH CONFIGURATION Release ===

    Check dependencies “Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly. “Use Legacy Swift Language Version” (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

    ** BUILD FAILED **

    opened by chadwilson 1
  • Use of unresolved identifier MotionKit: XCode 7.3.1

    Use of unresolved identifier MotionKit: XCode 7.3.1

    Hi, MotionKit looks like an awesome framework but I can't make it work. I've installed it using Cocoapods following the instructions and i got the error "use of unresolved identifier MotionKit". If i import MotionKit, i got "no such module MotionKit".

    I've tried installing it manually by importing MotionKit.swift and everything seems to be recognized but the MotionKit.swift file has 16 issues that make the build fail.

    Is anyone working on supporting MotionKit for the latest version of XCode and Swift? If not, has anyone found a workaround?

    Thanks

    opened by cbalsalobre 3
Releases(0.8.1)
Owner
Muhammad Haroon Baig
Muhammad Haroon Baig
Luminous provides you a lot of information about the system and a lot of handy methods to quickly get useful data on the iOS platform.

Luminous Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 8+ Swift 5 Xcode 1

Andrea Mario Lufino 324 Nov 27, 2022
Simply the fastest way to transmit data between iOS/tvOS and OSX

DarkLightning DarkLightning is a lightweight Swift library to allow data transmission between iOS/tvOS devices (Lightning port, Dock connector, USB-C)

Jens Meder 318 Nov 29, 2022
NFC Forum Well Known Type Data Parser for iOS11 and Core NFC

NFCNDEFParse NFC Forum Well Known Type Data Parser for iOS11 and Core NFC. Supports parsing of types: Text - NFCForum-TS-RTD_Text_1.0 2006-07-24 Uri -

Jari Kalinainen 14 Oct 21, 2022
A better way to operate QR Code in Swift, support iOS, macOS, watchOS and tvOS.

EFQRCode is a lightweight, pure-Swift library for generating stylized QRCode images with watermark or icon, and for recognizing QRCode from images, in

EFPrefix 4.3k Jan 2, 2023
AirQualityMonitoring - Here display the live air quality monitoring data

AirQualityMonitoring Here display the live air quality monitoring data. Details

MdNiks 0 Jan 28, 2022
AmiiboReader - Reading data from amiibo by using Core NFC

AmiiboReader Reading data from amiibo by using Core NFC NTAG215 Data Sheet https

Shinichiro Oba 7 Mar 24, 2022
You will learn how to scan QR code with iOS framework.

QR Code Scanner You will learn how to scan QR code with in iOS without using any library. It is as simple to scan QR code in iOS. In this example, We

Nitin Aggarwal 11 Dec 8, 2022
🛰 CoreLocation Made Easy - Efficient & Easy Location Tracker, IP Location, Gecoder, Geofence, Autocomplete, Beacon Ranging, Broadcaster and Visits Monitoring

Location Manager Made Easy SwiftLocation is a lightweight Swift Library that provides an easy way to work with location-related functionalities. No mo

Daniele Margutti 3.2k Dec 30, 2022
A camera view controller with custom image picker and image cropping.

ALCameraViewController A camera view controller with custom image picker and image cropping. Features Front facing and rear facing camera Simple and c

Alex Littlejohn 2k Dec 29, 2022
:mag_right: A simple and beautiful barcode scanner.

Description BarcodeScanner is a simple and beautiful wrapper around the camera with barcode capturing functionality and a great user experience. Barco

HyperRedink 1.6k Jan 3, 2023
Library for iOS Camera API. Massively increase performance and ease of use within your next iOS Project.

CameraKit helps you add reliable camera to your app quickly. Our open source camera platform provides consistent capture results, service that scales,

CameraKit 628 Dec 27, 2022
Swift library to easily check the current device and some more info about it.

Usage To run the example project, clone the repo, and run pod install from the Example directory first. let device = Deviice.current device is a Devi

Andrea Mario Lufino 56 Nov 3, 2022
Light weight tool for detecting the current device and screen size written in swift.

Device detect the current  device model and screen size. Installation CocoaPods Device is available through CocoaPods. To install it, simply add the

Lucas Ortis 1.5k Dec 28, 2022
WatchCon is a tool which enables creating easy connectivity between iOS and WatchOS.

WatchCon WatchCon is a tool which enables creating easy connectivity between iOS and WatchOS Requirements iOS 9.0+ / watchOS 2.0+ CocoaPods CocoaPods

Abdullah Selek 33 Sep 22, 2022
Lightweight Cocoa library for detecting the running device's model and screen size.

Lightweight Cocoa library for detecting the running device's model and screen size. With the newer  devices, developers have more work to do. This li

Sebastian Dobrincu 1.3k Nov 24, 2022
Writes twitter and contact (links) to writable nfcs on iPhone 7+ iOS 14+

nfc writer ios app nfc writer app is a hacky fun side project that writes twitter and contact (links) to writable nfcs. runs on iPhone 7+ iOS 14+. joi

Vivian Phung 5 Nov 23, 2022
An iOS framework to easily create a beautiful and engaging onboarding experience with only a few lines of code.

Onboard Click Here For More Examples Important Onboard is no longer under active development, and as such if you create any issues or submit pull requ

Mike 6.5k Dec 17, 2022
⏲ A tiny package to measure code execution time. Only 20 lines of code.

Measure ⏲ A tiny package to measure code execution time. Measure.start("create-user") let user = User() Measure.finish("create-user") Console // ⏲ Mea

Mezhevikin Alexey 3 Oct 1, 2022
A very useful and unique iOS library to open image picker in just few lines of code.

ImagePickerEasy A very simple solution to implement UIImagePickerController() in your application. Requirements Swift 4.2 and above Installation Image

wajeehulhassan 6 May 13, 2022
A SwiftUI framework which makes it easy to integrate Video Call and Chat within a few lines of code.

Welcome to iStream! This SwiftUI Framework allows you to add Video Call and Chat to your project within a few lines of code. To use this Framework, yo

null 2 Aug 19, 2022