ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP4126Sensor Data Shake Api
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP4126

    Mobile Application Development 2

    Progress0 / 38 done
    Topics38
    1Understanding Xcode2Using the Xcode interface builder and objects library3Understanding view hierarchy and creating a custom app icon
    4Understanding outlets and actions5Using text fields, buttons, labels, web views, and page controllers6Using views with subviews and creating views using code
    7Working with the single view template8Exploring the app delegate and adding new view controllers9Transitioning between multiple view controllers using animations
    10Tabbar and master detail templates
    11Customizing for different inputs12Adjusting text field behaviors and dismissing the keyboard13Detecting keyboard activities with notification center14Using scroll view and responding to keyboard activities programmatically
    15Detecting device hardware16Dynamically adjusting graphical layouts and creating universal apps
    17Understanding UITableView and UITableViewCell18Working with UITableView data source and delegate19Master detail template, drill-down menus, and navigation20Using property lists for data persistence and creating multi-section tables
    21Portrait and landscape modes22Handling device rotation and forcing specific orientation23Dynamically adjusting layouts based on rotation
    24Importing sqlite3 and creating a database25Writing tables, inserting records, and bundling a database with your app26Checking for database existence and reading/displaying data
    27NSTimer class and object transformations28Rotation, scaling, translation, animating image arrays, and playing video
    29Email, Safari, and SMS30Working with camera and photo library
    31Consuming and parsing XML and JSON32Integrating Twitter and Facebook with iOS apps
    33MapKit and MKMapView34Getting and displaying user location and directional information35Displaying map annotations, disclosure buttons, and reverse geocoding36Working with iCloud
    37Gyroscope and accelerometer38Outputting sensor data and using the Shake API
    3 min read
    Topic 38 of 38
    Topic Study Note Illustration
    38

    Outputting sensor data and using the Shake API

    It means reading motion sensor values (accelerometer/gyroscope) and displaying them in the app UI or console.

    📳 Outputting Sensor Data & Using the Shake API (iOS – Core Motion)


    ✅ 1. Definition

    🔹 Sensor Data Output

    It means reading motion sensor values (accelerometer/gyroscope) and displaying them in the app UI or console.

    👉 Example:

    • Showing X, Y, Z acceleration values on screen
    • Updating labels in real time

    🔹 Shake API

    The Shake API detects when a user physically shakes the iPhone/iPad.

    👉 Used for:

    • Undo action
    • Refresh data
    • Random actions (dice apps)

    🧠 2. Key Concepts

    🔹 Core Motion Framework

    Used to access:

    • Accelerometer data
    • Gyroscope data
    • Shake detection

    🔹 UIResponder Motion Events

    iOS provides built-in methods for shake detection:

    • motionBegan
    • motionEnded
    • motionCancelled

    ⚙️ 3. Import Required Framework

    import CoreMotion
    

    📊 4. Outputting Accelerometer Data


    🔹 Step 1: Create Motion Manager

    let motionManager = CMMotionManager()
    

    🔹 Step 2: Start Accelerometer Updates

    motionManager.accelerometerUpdateInterval = 0.2
    
    motionManager.startAccelerometerUpdates(to: OperationQueue.main) { data, error in
        
        if let acceleration = data?.acceleration {
            
            print("X: \(acceleration.x)")
            print("Y: \(acceleration.y)")
            print("Z: \(acceleration.z)")
        }
    }
    

    🔹 Step 3: Display in UI Labels

    xLabel.text = "X: \(acceleration.x)"
    yLabel.text = "Y: \(acceleration.y)"
    zLabel.text = "Z: \(acceleration.z)"
    

    📊 5. Sensor Data Flow Diagram

    Device Movement
          ↓
    Accelerometer / Gyroscope
          ↓
    CMMotionManager
          ↓
    Swift Code (Output Data)
          ↓
    UI Labels / Console
    

    📳 6. Shake API (Detect Device Shake)


    🔹 Step 1: Enable First Responder

    override var canBecomeFirstResponder: Bool {
        return true
    }
    

    🔹 Step 2: Become First Responder

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        becomeFirstResponder()
    }
    

    🔹 Step 3: Detect Shake Motion

    override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        
        if motion == .motionShake {
            print("Device shaken!")
        }
    }
    

    🔹 Step 4: Perform Action on Shake

    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        
        if motion == .motionShake {
            label.text = "Shaken!"
            view.backgroundColor = .random()
        }
    }
    

    🎲 7. Example App

    🎯 Shake Dice App

    • User shakes device
    • App generates random number
    • Displays dice result
    • Changes image or label

    📊 8. Shake Event Flow

    User Shakes Device
            ↓
    motionBegan()
            ↓
    motionEnded()
            ↓
    App Executes Action
            ↓
    UI Updates (Label/Image/Color)
    

    💡 9. Example Use Cases

    • 🎲 Dice rolling app
    • 🔄 Refresh news feed
    • ↩️ Undo last action
    • 🎮 Game controls
    • 📱 Fun interactive effects

    📌 10. Important Rules / Tips

    • Always call becomeFirstResponder()
    • Shake detection works only on physical device
    • Stop motion updates when not needed
    • Use main thread for UI updates
    • Avoid heavy processing in shake event

    ⚠️ 11. Common Mistakes

    • ❌ Shake not detected (forgot first responder)
    • ❌ Testing shake on simulator
    • ❌ Not enabling motion events properly
    • ❌ Updating UI on background thread
    • ❌ Leaving motion updates running

    🧠 12. Best Practices

    • Use shake only for simple actions
    • Combine sensor data for better UX
    • Keep UI responsive during motion updates
    • Stop accelerometer when not needed
    • Use shake for fun or quick actions

    📝 13. Likely Exam Questions

    1. What is sensor data in iOS?
    2. How do you display accelerometer data?
    3. What is the Shake API used for?
    4. Write code to detect device shake.
    5. What is motionBegan method?
    6. Why is Core Motion used?
    7. Explain shake event flow with diagram.
    8. Give examples of Shake API usage.

    📚 14. Quick Revision Summary

    • Sensor data = accelerometer + gyroscope values

    • Output = display data in UI or console

    • Shake API detects device shake motion

    • Uses:

      • motionBegan
      • motionEnded
    • Requires becomeFirstResponder()

    • Used in:

      • Games
      • Refresh features
      • Interactive apps

    ← Previous topic 37
    Working with the Accelerometer: Gyroscope and accelerometer

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    3mremaining
    590words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Mobile Application Development 2