Pastoral

Press a tab to play a selection from each movement of Beethoven’s Pastoral Symphony. For a cartoon treatment, see the 1940 Disney Fantasia.

This app has a row of five ViewControllers under a UITabBarController. Each of these ViewControllers has two methods, viewDidAppear(_:) and viewWillDisappear(_:), that are called automatically when the ViewController’s view appears and disappears as a result of the user pressing the tabs. It would seem that these two methods should play and stop the audio file belonging to each ViewController. And in fact, the viewWillDisappear(_:) method does stop the sound.

Why don’t we start the sound in viewDidAppear(_:)? Well, if we did that, the audio file of the First Movement would start playing automatically as soon as the app was launched. But we don’t want to play any audio file until the user presses a tab. That’s why we need a UITabBarControllerDelegate.

Our application delegate acts as the UITabBarControllerDelegate of the UITabBarController. The tabBarController(_:didSelectViewController:) method of this delegate is called whenever we press a tab. Our implementation of this method plays the audio file of the view controller belonging to that tab. If we press the same tab again while the music is playing, it will immediately restart the file from the beginning.

Source code in Pastoral.zip

  1. Class AppDelegate. The application delegate populates the tab bar controller with an array of five ViewControllers. The application delegate is also the delegate of the tab bar controller.
  2. Class ViewController. There are five of them, all sharing the same icon. The view that each one creates is a simple UILabel.
  3. 1.mp3 (Allegro ma non troppo)
  4. 2.mp3 (Andante molto mosso)
  5. 3.mp3 (Allegro)
  6. 4.mp3 (Allegro)
  7. 5.mp3 (Allegretto)
  8. Images.xcassets, an Xcode asset catalog file. Apple prefers .png format.
    1. icon.imageset
      1. Contents.json: a JSON file listing the files belonging to the icon image set.
      2. icon.pdf: one of the files belonging to the icon image set. 30 × 30 pixels.

Create the project

See Gone for adding an audio file to a project. Class ViewController must import the AVFoundation framework.

See TabBar for adding a tab bar icon to a tab bar controller. I got this icon by creating a new project and selecting “Tabbed Application” instead of “Empty Application” as the template for the project. Then I copied the file
/Users/myname/Desktop/Projectname/projectname/Images.xcassets/second.imageset/second.pdf
to my Mac Desktop and renamed it icon.pdf.

Output from print

First did appear.
First was selected.
First will disappear.
Second was selected.
Second did appear.
Second will disappear.
Third was selected.
Third did appear.
Third will disappear.
Second was selected.
Second did appear.
etc.