medics
medics

Reputation: 15

SwiftUI: how to detect volume button pressed (hardware)?

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.

Upvotes: 1

Views: 2279

Answers (1)

Michael C
Michael C

Reputation: 166

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

Upvotes: 3

Related Questions