0

I'm trying to get when you press the play / pause button of my earpods make an action. For this I am first trying to achieve change a text label ...

According to look at various websites, they performed this same but it does not work. Is there anything missing me add?

I have the following code in viewController.swift

override func viewDidLoad() {
    super.viewDidLoad()
    canBecomeFirstResponder()
    UIApplication.sharedApplication().beginReceivingRemoteControlEvents()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBOutlet weak var Cosa: UILabel!

func play()  {
    Cosa.text = "Play"
}

override func canBecomeFirstResponder() -> Bool {
    return true
}

override func remoteControlReceivedWithEvent(event: UIEvent?) {
    guard let event = event else {
        print("no event\n")
        return
    }
    guard event.type == UIEventType.RemoteControl else {
        print("received other event type\n")
        return
    }
    switch event.subtype {
    case UIEventSubtype.RemoteControlPlay:
        print("received remote play\n")
        play()
    case UIEventSubtype.RemoteControlPause:
        print("received remote pause\n")
    case UIEventSubtype.RemoteControlTogglePlayPause:
        print("received toggle\n")
    default:
        print("received \(event.subtype) which we did not process\n")
    }
}
user5535857
  • 33
  • 1
  • 4
  • Unrelated to your question, but a code comment: Your IBOutlet "Cosa" should begin with a lowercase letter. In Obj-c and Swift names beginning with uppercase letters are expected to be Types. Member values, properties and methods should all begin with lowercase letters. – alexkent Oct 16 '16 at 19:11

1 Answers1

1

For any RemoteControlEvents you need to have the audio playing.

Preparing Your App for Remote Control Events

To receive remote control events, do the following:

  1. Register handlers for each action you support. Use the shared MPRemoteCommandCenter object to register handlers for different types of events
  2. Begin playing audio. Your app must be the “Now Playing” app. An app does not receive remote control events until it begins playing audio.

https://developer.apple.com/library/content/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/Remote-ControlEvents/Remote-ControlEvents.html

Also you can refer the below link for more clarification and Demo project Receive remote control events without audio

Community
  • 1
  • 1
Annie Gupta
  • 2,786
  • 15
  • 23