Add Action To Apple TV Remote Play/Pause Button - swift

I have an AVAudioPlayer in my app and I am adding a function where the user can press the Play/Pause button on the remote to Play/Pause the AVAudioPlayer. I have this code in my App Delegate:
func initializePlayButtonRecognition() {
addPlayButtonRecognizer(#selector(AppDelegate.handlePlayButton(_:)))
}
func addPlayButtonRecognizer(_ selector: Selector) {
let playButtonRecognizer = UITapGestureRecognizer(target: self, action:selector)
playButtonRecognizer.allowedPressTypes = [NSNumber(value: UIPressType.playPause.rawValue as Int)]
self.window?.addGestureRecognizer(playButtonRecognizer)
}
func handlePlayButton(_ sender: AnyObject) {
if audioPlayer.isPlaying {
audioPlayer.pause() {
} else {
audioPlayer.play()
}
}
}
The AVAudioPlayer's name is an audio player. I have that stated in the code, but the App Delegate does not have a reference to the AVAudioPlayer from the PlayerViewController. How do I do this?

Your code looks correct. Just a missing detail that could explain why it does not work as expected... in tvOS, apart from setting allowedPressTypes it is also needed to define allowedTouchTypes as indirect:
playButtonRecognizer.allowedTouchTypes = [NSNumber(value: UITouchType.indirect.rawValue)]

Related

Swift - How to get the sender tag for an array of buttons using UILongPressGestureRecognizer?

I have buttons in the storyboard that I put into a Referencing Outlet Collection. I'm using UITapGestureRecognizer and UILongPressGestureRecognizer for all of these buttons, but how can I print exactly which button gets tapped? Bellow is what I tried but doesn't work. I get an error that says "Value of type 'UILongPressGestureRecognizer' has no member 'tag'." I'm trying to build the button grid for the Minesweeper game. Thank you for your help.
class ViewController: UIViewController {
#IBOutlet var testButtons: [UIButton]! // There are 100 buttons in this array
override func viewDidLoad() {
super.viewDidLoad()
let testButtonPressed = UILongPressGestureRecognizer(target: self, action: #selector(testPressed))
testButtonPressed.minimumPressDuration = 0.5
// These indexes are just to test how to recognize which button gets pressed
testButtons[0].addGestureRecognizer(testButtonPressed)
testButtons[1].addGestureRecognizer(testButtonPressed)
}
#objc func testPressed(_ sender: UILongPressGestureRecognizer) {
print("Test button was pressed")
print(sender.tag) // THIS DOESN'T WORK, BUT CONCEPTUALLY THIS IS WHAT I WANT TO DO
}
This error occurs because UILongPressGestureRecognizer object has no tag property
You can access sender's button in a way like that:
#objc func testPressed(_ sender: UILongPressGestureRecognizer) {
guard let button = sender.view as? UIButton else { return }
print(button.tag)
}
I think that the best solution to handle button's actions is to add #IBAction
(you can add it like #IBOutlet with a minor change - set Action connection type)
And then in #IBAction block you cann access all button properties (like tag and others)
instead of using gesture I think it would be better to use #IBAction and connect the buttons With it here is a small example
UILongPressGestureRecognizer which is a subclass of UIGestureRecognizer, can be used only once per button or view. Because UILongPressGestureRecognizer has only a single view property. In your code, it will always be testButtons[1] calling the testPressed action. So you have to first modify the viewDidLoad code like this :-
for button in testButtons {
let testButtonPressed = UILongPressGestureRecognizer(target: self, action: #selector(testPressed))
testButtonPressed.minimumPressDuration = 0.5
button.addGestureRecognizer(testButtonPressed)
button.addGestureRecognizer(testButtonPressed)
}
Then you can access the button from testPressed like this (I hope you've already set the tag in the storyboard) :-
#objc func testPressed(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
if let button = sender.view as? UIButton {
print(button.tag)
}
}
}
You need to set tags before pressing!
On the viewDidLoad() method you must add something like:
testButtons.enumerated().forEach {
let testButtonPressed = UILongPressGestureRecognizer(target: self, action: #selector(testPressed))
testButtonPressed.minimumPressDuration = 0.5
$0.element.addGestureRecognizer(testButtonPressed)
$0.element.tag = $0.offset
}
And when the long press is receiving you need to get a tag from view not from the sender!
print(sender.view?.tag)
Since a gesture recognizer should only be associated with a single view, and doesn't directly support using an identity tag to match it with buttons. When creating an array of buttons for a keyboard, with a single gesture response function, I found it easier to use the gesture recognizer "name" property to identify the associated button.
var allNames: [String] = []
// MARK: Long Press Gesture
func addButtonGestureRecognizer(button: UIButton, name: String) {
let longPrssRcngr = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressOfButton(gestureRecognizer:)))
longPrssRcngr.minimumPressDuration = 0.5
longPrssRcngr.numberOfTouchesRequired = 1
longPrssRcngr.allowableMovement = 10.0
longPrssRcngr.name = name
allNames.append(name)
button.addGestureRecognizer(longPrssRcngr)
}
// MARK: Long Key Press
#objc func longPressOfButton(gestureRecognizer: UILongPressGestureRecognizer) {
print("\nLong Press Button => \(String(describing: gestureRecognizer.name)) : State = \(gestureRecognizer.state)\n")
if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
if let keyName = gestureRecognizer.name {
if allNames.contains(keyName) {
insertKeyText(key: keyName)
} else {
print("No action available for key")
}
}
}
}
To implement, call the addButtonGestureRecognizer function after creating the button, and provide a name for the button (I used the button text) e.g.
addButtonGestureRecognizer(button: keyButton, name: buttonText)
The button name is stored in the "allNames" string array so that it can be matched later in "longPressOfButton".
When the button name is matched in the "longPressOfButton" response function, it passes it to "addKeyFunction" where it is processed.

MPRemoteCommandCenter play/pause Flashing when touched

i'm working on music player app that written in Swift, audio streams with AVPlayer and everything is fine
but when i tried to add MPRemoteCommandCenter to my app there was a lot of bug that i dont know even why this happend
link to video that describes my problem
AVPlayer Implemented like:
func setupPlayer() {
let item = AVPlayerItem(url: musicURL)
self.player = AVPlayer.init(playerItem: item)
self.player.play()
self.player.volume = 1
self.player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: DispatchQueue.main, using: { (time) in
if self.player.currentItem?.status == .readyToPlay {
self.reloadNowPlayingInfo()
let currentTime = self.player.currentTime().seconds
self.playingTime.text = currentTime.getTimeString()
self.playerSlider.value = currentTime/duration
}
})
}
func reloadNowPlayingInfo() {
var info = [String : Any]()
info[MPMediaItemPropertyTitle] = self.titleText
info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork.init("some image")
info[MPMediaItemPropertyPlaybackDuration] = seconds
info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = currentSecs
info[MPMediaItemPropertyArtist] = "Artist name"
MPNowPlayingInfoCenter.default().nowPlayingInfo = info
}
and for command center,
MPRemoteCommandCenter Implemented like:
func setupCommandCenter() {
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.pauseCommand.isEnabled = true
commandCenter.playCommand.addTarget(self, action: #selector(self.playCommand(_:)))
commandCenter.pauseCommand.addTarget(self, action: #selector(self.pauseCommand(_:)))
}
#objc func playCenter(_ action: MPRemoteCommandEvent) {
self.state = .play
self.playBtn.setBackgroundImage("some image"), for: .normal)
self.player.play()
self.fetchTracks()
}
#objc func pauseCenter(_ action: MPRemoteCommandEvent) {
self.state = .pause
self.playBtn.setBackgroundImage("some image"), for: .normal)
self.player.pause()
self.fetchTracks()
}
In addition to the code you've presented you might also have called the following somewhere in your app delegate:
UIApplication.shared.beginReceivingRemoteControlEvents()
Doing this in addition to using MPRemoteCommandCenter.shared() seems to cause a race condition.
According to Apple's documentation:
In iOS 7.1 and later, use the shared MPRemoteCommandCenter object to register for remote control events. You do not need to call this method when using the shared command center object.
This method starts the delivery of remote control events using the responder chain.
Remove that method from your app delegate and you should be fine.
If you add 2 observer to your code to receive player notifications. you may see lag or jump in player lock screen.
avoid adding observer and once a target.
commandCenter.playCommand.addTarget(self, action: #selector(self.playCommand(_:)))
only once. and remove it when u dont wanted

Type of expression is ambiguous without more context AVAudioSession

I'm trying to add notification observer to detect when headphones are removed and the music stop playing. I followed Audio Session. I'm trying to search Swift 4.2 syntax, changed some things from the original code from Apple but I still get this error:
Type of expression is ambiguous without more context
What am I doing wrong? Let me know if I need to add more code
override func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChanged), name: .AVAudioSession.routeChangeNotification, object: nil)
//Error this line: Type of expression is ambiguous without more context
}
#objc func audioRouteChanged(notification: Notification) {
guard let userInfo = notification.userInfo else { return }
guard let reason = userInfo[AVAudioSessionRouteChangeReasonKey] as? Int else { return }
if reason == AVAudioSession.RouteChangeReason.oldDeviceUnavailable.hashValue {
// headphones plugged out
// continue playback or change the play/pause icon
playPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal)
miniPlayPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal)
}
}
Remove the dot before AVAudioSession name: .AVAudioSession.routeChangeNotification

avplayer with slow-internet connection not working after first frame

my problem is that when having very bad connection,the activtiy indicator start animating till first frame in video is shown,then disappear thinking is the video is playing,but the video stops playing stuck on loaded first frame,until the whole video is loaded then its resume playing,how to show activity indicator while video is stuck on frame and buffering ,then play until next loaded frame ?
notes:
it's working when internet connetion is off ,video is played until the loaded frame and activity indicator is shown,then when turn on video us resumed to play and activity indicator is hidden
it's working when normal internet connection is present
removing and showing indicator using override observevalue for key path
"currentItem.loadedTimeRanges"/"currentItem.playbackBufferEmpty"
i made a uiview class with avplayer in it
import UIKit
import AVKit
import AVFoundation
class videoplaying: UIView {
override static var layerClass: AnyClass {
return AVPlayerLayer.self;
}
var playerlayer: AVPlayerLayer{
return layer as! AVPlayerLayer;
}
var player: AVPlayer?{
get{
return playerlayer.player
}
set {
playerlayer.player = newValue
}
}
var playetitem: AVPlayerItem?
}
i assigned a uivew in uicollectioncell to this class(using storyboard)
avplayer starts playing and adding observes when pressing play in uicollectioncell
#IBAction func play(_ sender: Any) {
activityindicator.isHidden = false
activityindicator.startAnimating()
self.butttoonheight.isHidden = true
self.postimage.isHidden = true
let url2 = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let avplayer = AVPlayer(url: url2! )
let playeritem = AVPlayerItem(url: url2!)
//videoss is class of type uiview
videoss.playetitem = playeritem
videoss.playerlayer.player = avplayer
videoss.player?.play()
videoss.player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
videoss.player?.addObserver(self, forKeyPath: "rate", options: .new
, context: nil)
videoss.player?.addObserver(self, forKeyPath: "currentItem.playbackBufferEmpty", options: .new, context: nil)
playying.isHidden = false
}
//observing when video is playing
//playpause button to play or pause video while bad network is present video is stuck on first frame and playorpause is not changing while pressed
#IBAction func playorpause(_ sender: Any) {
if videoss.player?.timeControlStatus == AVPlayerTimeControlStatus.paused{
videoss.player?.play()
playying.setImage(UIImage(named: "pas50"), for: .normal)
}
if videoss.player?.timeControlStatus == AVPlayerTimeControlStatus.playing{
videoss.player?.pause()
playying.setImage(UIImage(named: "p24"), for: .normal)
}
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate"{
print(videoss.player?.rate)
if videoss.player?.rate == 0.0 {
print("dawdaopwdaopwdipo")
}
}
if keyPath == "currentItem.loadedTimeRanges"{
print("its is working")
activityindicator.stopAnimating()
activityindicator.isHidden = true
}
if keyPath == "currentItem.playbackBufferEmpty"
{
activityindicator.startAnimating()
activityindicator.isHidden = false
print("pkawdawdawd")
}
}
I solved this problem by adding a timer that runs ever 0.3 seconds,evrry 0.3seconds it checks the current time of the video if current time equals previous time then the video is not playing activity indicator is shown,if not video if playing activity indicators was hidden,also you need to check if the users pause the video,an advantage is you also get the current time also in the same function.
What i tried also was seeing rate of the video ,but over slow internet the rate was always giving that is playing,but it wasn’t,which didn’t help

use a slider while pressing button swift

Using Xcode 8, Swift 3 and Interface Builder with Storyboards and a very basic view controller featuring only a button (Play) and a slider (volume).
I'm trying to use my NSSlider while pressing a button at the same time. For instance, I need to be able to keep pressing "Play" while slowly lowering the volume. What happens instead is that only one button can be in use at a time. So, as long as I am pressing "Play" using the return key, I can't adjust the volume and vice versa.
In this example, the Play button is triggered by the "return" key.
Here is the code in ViewController.swift. This is just an example app I created quickly to study the problem.
Is there an Interface Builder setting on the NSSLider that I am missing, or can I do something in my code to achieve what I am trying to do?
import Cocoa
import AVFoundation
class ViewController: NSViewController {
var audioPlayer = AVAudioPlayer()
var sliderValue: Float = 0
#IBOutlet weak var volumeSliderOutlet: NSSlider!
override func viewDidLoad() {
super.viewDidLoad()
do{
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "bell ding", ofType: "wav")!))
}
catch {
print(error)
}
audioPlayer.prepareToPlay()
// Do any additional setup after loading the view.
}
#IBAction func playButtonAction(_ sender: NSButton) {
if audioPlayer.isPlaying {
audioPlayer.currentTime = 0.0
audioPlayer.play()
} else {
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
#IBAction func volumeSliderAction(_ sender: NSSlider) {
if audioPlayer.isPlaying {
sliderValue = self.volumeSliderOutlet.floatValue
audioPlayer.volume = sliderValue
} else {
return
}
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
I've also tried this, based on advice from #inspector_60, but it doesn't work either. Still can't handle the slider while continuing to press the shortcut key for the button "return".
override func keyDown(with event: NSEvent) {
if (event.keyCode == 36) {
self.playButtonAction(nil)
}
else {
return
}
}
func playButtonAction(_ sender: NSButton?) {
if audioPlayer.isPlaying {
audioPlayer.currentTime = 0.0
audioPlayer.play()
} else {
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
IBAction are UI events so not suitable for multiple simultaneous clicks (you have only one mouse pointer). Use handling key events in order to handle keyboard events for simultaneous actions.
You need to also implement the mouse events, these links should help:
Apple document about mouse events and specifically Filtering Out Key Events During Mouse-Tracking Operations
This stack overflow answer on how to implement this approach
This post that will give you more information and example - Ron's answer links to a question not that different from yours