0

I want to detect volume button pressed, not just when volume change.

How would you do this for SwiftUI?

All the answers on stack-overflow are for Swift or Objective-C.

Detect hardware volume button press when volume not changed

EDIT:

Thank you @Michael C for the answer.

I guess there is no easy way to do it in SwiftUI. Guess I'll have to do an objective-c wrapper.

medics
  • 5
  • 3

1 Answers1

2

I have had a hard time with this problem as well. I came across this project https://github.com/jpsim/JPSVolumeButtonHandler and it does the job for the most part and even hides the volume indicator when the volume buttons are pressed.

This is what I did to get it to work. I hope that it helps.

import SwiftUI
import JPSVolumeButtonHandler

struct MyView: View {

    @State private var volumeHandler: JPSVolumeButtonHandler?

    var body: some View {
        ZStack {
            Text("Hello World")
        }
        .onAppear {
            // Setup capture of volume buttons
            volumeHandler = JPSVolumeButtonHandler(up: {
                // Code to run when volume button released
            }, downBlock: {
                // Code to run when volume button pressed
            })

            // Start capture of volume buttons 
            volumeHandler?.start(true)
        }
        .onDisappear {
            // Stop capture of volume buttons when leaving view
            volumeHandler?.start(false)
        }
    }

}

This is the post I used to figure it out originally: iOS. Capturing photos with volume buttons

Michael C
  • 96
  • 1
  • 8
  • 1
    Just a small change instead of volumeHandler?.start(false) we need to write volumeHandler?.stop() to removeObserver properly. – Mayur Tanna Mar 12 '23 at 04:31
  • Don't forget to call volumeHandler.startHandler(disableSystemVolumeHandler: false) before assigning the up/down blocks – C0D3 Jul 03 '23 at 01:18
  • 1
    If you'd like a Swift implementation of the same library, you can find it here: https://github.com/CipherBitCorp/VolumeButtonHandler – C0D3 Jul 26 '23 at 15:09
  • Thank you @C0D3, your swift implementation works well. – Michael C Aug 14 '23 at 19:40
  • No problem, there is actually small bug with it that I didn't get around to fixing yet but I'll update the library once I do. – C0D3 Aug 15 '23 at 06:38