NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

SOLVED: Thread 1: Exception: "-[Blackjackk_copy6.GameScene didTapButton]: unrecognized selector sent to instance 0x7fae512055b0"

Forums > Swift

I have a function to start and stop background music during a card game , the app builds and works ok but when the music button is pressed the above error comes up in app delegate. From what I can find the error is something to do with the line containing #selector. Any suggestions on how to get the error resolved would be appreciated.

   func setupButtons(){
   button = UIButton()
    button.frame = CGRect(x: 0, y: 0, width: self.view!.frame.width / 3, height: 60) = CGPoint(x:205, y:80)
    button.setTitle("music", for: UIControl.State.normal)
    button.backgroundColor = UIColor.darkGray
    button.layer.borderWidth = 5
    button.layer.cornerRadius = 10
    button.addTarget(self, action: #selector(MusicPlayer.didTapButton), for: UIControl.Event.touchUpInside)



       // play background music

       @objc func didTapButton(){
    if let player = audioPlayer, player.isPlaying{
        //stop playback
        button.setTitle("play", for: .normal)
    else {
        //set up player, and play
        button.setTitle("pause", for: .normal)
        let urlString = Bundle.main.path(forResource: "playlistbj", ofType: "mp3")

            try AVAudioSession.sharedInstance().setMode(.default)
            try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)

            guard let urlString = urlString else{
           audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: urlString))

            guard let player = audioPlayer else{

        catch {
            print ("oops")



button.addTarget(self, action: #selector(MusicPlayer.didTapButton), for: UIControl.Event.touchUpInside)

By using self as the first parameter to addTarget you are saying you will be calling a method on the current object. But the method you are passing in the action parameter exists as a class method on a MusicPlayer object. You should use this instead:

button.addTarget(self, action: #selector(didTapButton), for: UIControl.Event.touchUpInside)


thanks for the help, that has ticked one box of on my list.


Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

Not logged in

Log in

Link copied to your pasteboard.