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