I am learning Swift, and I am throwing myself in the deep end by building an app to force myself to learn the language. Something I want to implement is that when I transfer from screen 1 to screen 2, audio is played without needing to do anything. The audio is A-14a. The code below is set up so that when I click the Directions button, it plays the audio, but I don’t know how to do it right away. Images are below to help show what I mean.
The code I have is below:
import UIKit
import AVFoundation
class Intervention_Numerals1: UIViewController {
@IBOutlet weak var Directions: UIButton!
@IBOutlet weak var Done: UIButton!
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
setUpElements()
//Audio Test
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "A-N14a", ofType:"mp3")!))
audioPlayer.prepareToPlay()
} catch {
print(error)
}
}
func setUpElements() {
// Style the elements
Utilities.styleFilledButton(Directions)
Utilities.styleFilledButton(Done)
}
@IBAction func Play(_ sender: Any) {
audioPlayer.play()
}
}
Please let me know any advice on how to do this
2
Answers
Use this method
There are a couple of methods you can override to know the state of the view controller and add code to run when that state occurs.
As mentioned by Amila what you are looking for is probably
viewDidAppear
,Another method that might also help you achieve this is
viewWillAppear
I will provide the code of most of these methods and what they do below so you can try them all and experiment with them:
There are a few more of these such as
viewWillLayoutSubviews
andviewDidLayoutSubviews
that occur when views inside your View Controller change.Use all these to control when what happens, hope this helps 🙂