ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development 2
    COMP4126
    Progress0 / 38 topics
    Topics
    1. Creating an iOS App: Understanding Xcode2. Using the Xcode interface builder and objects library3. Understanding view hierarchy and creating a custom app icon4. Outlets, Actions, and Views: Understanding outlets and actions5. Using text fields, buttons, labels, web views, and page controllers6. Using views with subviews and creating views using code7. Using View Controllers: Working with the single view template8. Exploring the app delegate and adding new view controllers9. Transitioning between multiple view controllers using animations10. Application Templates: Tabbar and master detail templates11. The iOS Keyboard: Customizing for different inputs12. Adjusting text field behaviors and dismissing the keyboard13. Detecting keyboard activities with notification center14. Using scroll view and responding to keyboard activities programmatically15. Working with Different iOS Devices (iPhone & iPad): Detecting device hardware16. Dynamically adjusting graphical layouts and creating universal apps17. Using Table Views: Understanding UITableView and UITableViewCell18. Working with UITableView data source and delegate19. Master detail template, drill-down menus, and navigation20. Using property lists for data persistence and creating multi-section tables21. Supporting Screen Rotations: Portrait and landscape modes22. Handling device rotation and forcing specific orientation23. Dynamically adjusting layouts based on rotation24. Working with Databases: Importing sqlite3 and creating a database25. Writing tables, inserting records, and bundling a database with your app26. Checking for database existence and reading/displaying data27. Using Animations & Video: NSTimer class and object transformations28. Rotation, scaling, translation, animating image arrays, and playing video29. Accessing Integrated iOS Apps: Email, Safari, and SMS30. Working with camera and photo library31. Using Web Services: Consuming and parsing XML and JSON32. Integrating Twitter and Facebook with iOS apps33. Working with iOS Maps and Location Services: MapKit and MKMapView34. Getting and displaying user location and directional information35. Displaying map annotations, disclosure buttons, and reverse geocoding36. Working with iCloud37. Working with the Accelerometer: Gyroscope and accelerometer38. Outputting sensor data and using the Shake API
    COMP4126›Outputting sensor data and using the Shake API
    Mobile Application Development 2Topic 38 of 38

    Outputting sensor data and using the Shake API

    3 minread
    590words
    Beginnerlevel

    📳 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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time3 min
      Word count590
      Code examples0
      DifficultyBeginner