In the last lesson, we got our skeleton project off of GitHub and we managed to link up an IBAction 1
with a single button on our Main.storyboard and that's the first button, this red button here, so 2
that whenever it's pressed the words "I got pressed" get printed into the debug console. 3
We're now pretty certain that our IBAction is linked to that red button and we can trigger some bit 4
of functionality to happen when we press on the button. 5
Now, of course, the actual functionality we want is to make it play a Xylophone note, but we don't know 6
how to do that yet. 7
Now, I could simply tell you, "Well, here's step A, 8
this is what you do," but it doesn't answer the question of, "Well, how did I know how to do it?" 9
Instead, I want to show you how we can use the Application Programming Interface Documentation which 10
is quite a mouthful, but essentially, just refers to the components that Apple have already built into 11
iOS that we can simply tap into and use, because Application Programming Interface takes like a whole 12
second to say 13
that people often refer to it as the API. 14
So the API for your TV would be something like turning the volume up and down or switching the TV on 15
and off or changing the channel number. 16
So the API docs for your TV would then be the instruction manual which you probably throw away. 17
But luckily for us, the Apple API Docs are hosted online and you can find them at developer.apple.com 18
and then in documentation. 19
So this is basically the instruction manual for programming 20
iOS apps. Nut just like most manuals, they're so information-dense. 21
And if you dig into each of these, you'll find that they have endless links after links after links and 22
it's really hard figuring out exactly what you need to do from the documentation. 23
Just like when my mom has a problem with her TV, she'll always call up tech support which is, basically, 24
me, instead of reading the actual instruction manual for her TV. 25
Well, programmers also don't usually start with the API Documentation, 26
instead, we tend to use the programmer's tech support which is StackOverflow. Now StackOverflow is basically 27
a Q-and-A website like Yahoo Answers or Quora, 28
but for people who code. So let's say I had a question and because programmers are programmers, there 29
are some crazy questions on here and some brilliant answers. 30
If you ever wanted to know what is the most efficient way of pairing socks from a pile, well, you could 31
search on StackOverflow and you'll see that somebody has asked this question six years ago with three 32
thousand upvotes. 33
That was a really popular question and we have a bunch of answers, in fact, two whole pages of answers 34
here. And the top answer got a lot of upvotes, as well as the checkmark which means that the original 35
person who asked the question has accepted this as the answer. 36
So if you ever want to know how to sort your socks in the fastest way possible, well, apparently, you could 37
use a hashing algorithm. Now because there are literally millions of things that you can make your iPhone 38
app do, 39
it will be impossible to remember all the names of those things that you need to use or the exact code 40
that you would need to write, 41
even things like how to change an image in an image view. You don't need to memorize the code ImageView.image. 42
You could just look it up. And in the answer, 43
people often provide a code snippet where they show you the answer or how to achieve what you want to 44
do. 45
So in this case, here's your ImageViewOutlet.image 46
= your Image, and then we would be able to set the image view. Whenever you want to solve a 47
problem in programming or when you want your code to do something specific, 48
then I recommend following this five-step process which we're going to go through by trying to figure 49
out how we can get our app to play sound. 50
Step 1 involves Google. 51
Step 2 involves going to StackOverflow. 52
Step 3, 53
implementing the code that you find there. 54
Step 4, looking up what the code means in the docs. 55
And step 5, customizing the code for your needs. 56
And we're gonna go through this step by step. 57
So let's start with the first one. 58
Now, ask any experienced programmer and they will tell you that a large part of getting good at programming 59
involves getting good at Googling. And two people with the same resources, say, a computer that's connected 60
to the internet don't always end up with the same solutions. 61
And some people might not even find a solution. 62
So when you're doing mobile app programming, I recommend following this search structure. 63
So, first, what I want my app to do. 64
Secondly, which programming language am I using. 65
And third, 66
which resource do I want to come up. 67
In our case, our search query will look something like this, Play sound using Swift on StackOverflow. 68
So let's try it out. In Google, 69
I'm gonna put in those exact search terms "play sound Swift using stackoverflow," and what we're looking 70
for is a website that starts out with stackoverflow.com. 71
So we're basically leveraging the power of Google's search engine to find the most relevant result on 72
StackOverflow. 73
Now you saw that we could also just search for our query in StackOverflow itself, but I find that Google 74
is far better at search algorithms than any other company. 75
Google looks at how often a search term leads to a click of a link, and then whether if the person stays 76
there, which means that they found the right resource for that search term, or whether if they head back 77
which means that they didn't find the right one and they have to look through the list. 78
So step one, basically, ensures that you get a more relevant result. 79
And once we found the StackOverflow answer that seems to most closely match what we want to do, in this 80
case, the question is how to play a sound using Swift? 81
That sounds pretty close to what we want to achieve, right? 82
Well, then we can go ahead and head over to StackOverflow and take a look at the question and answer 83
there. 84
This takes us onto step two, exploring the question-answer 85
on StackOverflow itself. And in this case, it's a good idea to take a look at the question to assess 86
whether if your own query is similar to what this person is asking for. In this case, they want to play 87
a sound using Swift and they had some code that worked previously, but it doesn't work in newer versions 88
of Swift. 89
So they want to know how do you do it now. 90
So if we scroll down, you can see that there are total of 13 answers that have been provided. And people 91
will often compete for highly voted questions because it means that their answers will get more exposure 92
and they're more likely to collect reputation points. 93
So every time you upvote somebody's answer or accept their answer as the correct answer, they get 94
reputation points which you can see down here. 95
And this is kind of like a game fight system to incentivize programmers to help each other, so that they 96
can gain reputation. And as you get better in your skills, it's a good idea to pass it forward, and help 97
people with what you know. And, also, when you go to job interviews as a programmer, by mentioning a really 98
high reputation on StackOverflow, 99
it also counts for a lot. 100
So it helps to help others. 101
Now, over here in the accepted answer, so the one with the green tick, you can see that they've provided 102
code snippets for how to implement this functionality of playing sound using various different versions 103
of Swift. 104
So it's Swift 2.3, 3, and 4. 105
I recommend looking for the latest version and anything from Swift 4 onward, so Swift 4, 106
5.2. 107
These are all pretty similar. 108
As long as you see something that is Swift 4 or Plus, then you should be all right 109
implementing the code. The order of the answers are presented in a specific way. 110
The first one that you will see is often the accepted answer. 111
So the one with the green tick on it. 112
And if you scroll down, you'll see the answers ordered by the number of upvotes, 113
at least this is the default order system. Now, because everything in development and programming moves 114
on so quickly, 115
just because the person asking the question accepted this answer back in, say, 2013, it doesn't mean that 116
it's still the best answer. 117
I always recommend students to take a look, not just at the top answer, but the top three to see if there's 118
something that's more relevant to today. 119
So now that we've found our answer on StackOverflow, it's time to go to step 3 and implement the sample 120
code in our app. 121
In this case, I'm actually going to use the top answer. 122
Not only was it accepted, but it's also got a whole bunch of different versions and it seems to be the 123
most compatible with where we are today. 124
Let's try and use this code snippet to implement it in our code and try to get our app to be able to 125
play sound. 126
So the first line of code I see here is this 127
import AVFoundation. 128
I'm going to put that into our project just below where we are importing UIKit. 129
I'm going to import the AVFoundation module. 130
Now, these modules are essentially the libraries of code that Apple is written to allow us to interact 131
with different parts of the hardware and to perform different tasks. 132
So in this case, the AVFoundation refers to the audiovisual foundational module. 133
Now that we've added the capability of interacting with the audio hardware, which is what this line does, 134
it's time to actually set up our audio player. 135
Notice how here we're creating a variable code player 136
and we're setting it to be a AVAudioPlayer 137
in our code. 138
So we're gonna create a variable code player and then we're going to add a colon to specify the data 139
type of our player which is gonna be AVAudioPlayer, 140
and then we add a question mark at the end. 141
Now, we're going to ignore this for now. 142
I'm going to explain it in a huge amount of detail later on. But for now, let's focus on trying to get 143
our sound playing ability to work first. 144
The next thing I'm going to do is I'm actually just going to copy this entire thing wholesale, 145
the rest of the code that's in the code snippet, and simply paste it into our project just above the 146
last closing brace, 147
so right about here. 148
Now, once I pasted it in here, 149
now we're going to have to do a little bit of modification because we don't actually have a resource 150
code sound name, 151
and with the extension of mp3 because we have sounds that are named like this C.wave, D.wave. 152
So we have to change these. 153
So I'm going to change this to a capital C, which looks exactly the same as the sound file, and I'm going 154
to change the extension to wave which is W-A-V, not W-A-V-E. 155
So now I've modified the sample code in the StackOverflow code snippet to work with our resource 156
and I'm going to leave everything else as it is. But because this play sound lists in a separate block of 157
code, I'm going to trigger it inside all keyPressed IBAction. So I'm going to delete that print statement 158
and instead, call this playSound functionality, so that when we press the red key, this block gets triggered 159
and it looks for this thing called playSound. It finds it right here, and then it executes all the code 160
in this block. 161
So let's hit run and see if it works. All right, 162
so here's my app and I'm gonna press on the top button, and you can hear that a sound is being played. 163
So now that we've achieved our first three steps, we've managed to implement the solution we found from 164
StackOverflow. 165
We're now ready to head over to step four which is to look at the Apple API Docs to understand what 166
the code does. I'm firstly going to delete all of the existing comments 167
that the person who provided the solution has put in there so that we only have the code, and then 168
I'm gonna head over to the API Documentation, and you can find that by heading over to 169
developerapple.com/documentation. 170
I'm going to search for that thing that we imported which was called AVFoundation to see what it does. 171
And the first result is the AVFoundation module that comes up. And this, as you can see, allows us to 172
work with audiovisual assets. 173
So, for example, our sound file to control cameras, to process audio, and to configure audio interactions. 174
So it seems to do a lot of things. And you can see that the documentation is split into different topics: 175
Playback and Editing, Media capture, Audio, et cetera. If we read through this, you can see that there's one part 176
that allows us to play, record, mix, and process audio. Playing or audio is pretty much what we wanted to 177
do, right? 178
So if we click through on this link, you can see that it gives you more details on how to play sound 179
using AVFoundation. 180
And it says that for playback of a single track, use AVAudioPlayer. And if we take a look at our code, 181
well, the AVAudioPlayer is exactly what we're using to play our sound. 182
Now, if we move down in our code, we can see that we've got this thing called a Bundle. 183
Now what exactly is a bundle? 184
So let's try and understand that by looking inside the documentation and searching for a Bundle. 185
Now if you click on the first link with the capital B for Bundle, then you can see that it's simply a 186
representation of the code and resources stored on the disk. And in our case, we're using the main Bundle 187
to locate our sound file resource. So if we ignore all the sort of programming keywords in pink, you can 188
see that we're essentially creating this constant code URL which is looking for a resource code 189
C.wave in all resources, 190
so the disk area allocated for our app. And then the next thing in our code that we're using, the next 191
sort of word that's really unfamiliar, is the AVAudiosession. 192
I'm going to copy this and look for it inside the docs by, again, going to the search bar and typing it. 193
And once we're here, then we're going to look for this thing called setCategory. What does setCategory actually do? 194
On this page AVAudiosession, I'm going to hit command F to find this set category. And if you 195
look through, you'll see where it tells us all about it. 196
So here, we could click through to this link and learn more about this setCategory and what it does. 197
Here we have a bit of discussion on how it works and you can find out that there's actually a whole 198
bunch of categories that we might want to use. 199
And the one that we're using is something called playback. 200
So on this page, we can see this ambient which means that the sound playback is nonprimary, 201
so your app can be used successfully with the sound turned off. 202
So then there's other types like solo ambient or record playback. 203
And this is one that we're using which is saying that the category for playing recorded music or other 204
sounds are central to the successful use of your app. Given that it's a musical app, then playing all sounds, 205
playing those notes is pretty central to the success of our app. 206
It's not just like background music in a game with some sound effects. 207
It's actually really important for that sound to come through. 208
So by setting in that category, even if the user had their phone on silent, we will still be able to get 209
our sound played because we're saying it is that important. 210
And if you read through the documentation, the entire documentation on AVAaudioSession, which is what 211
I did, then you'll find that there's this paragraph that explains to you that when in iOS, when the device 212
is locked, the apps audio is silenced. In iOS setting, the Ring/Silent switch to silent, silences any 213
audio being played by the app. 214
So this is the default audio session. And we had to use this line of code to change that default audio 215
session to a new category so that we can actually get our playback happening even if the phone is in 216
silent mode. 217
So notice how we're always researching the parts of the code that are sort of purple in color. 218
Well, that's because by the end of the course, you will know full well what each of the pink parts do 219
because these are these swift programming concepts. But you won't know all of the purple parts because 220
these come from Apple's Application Programming Interface Documentation. 221
So there are a myriad of things that you can do in there, anywhere from playing video to recording sound, 222
and it's not possible to cover all of the things that you can do. 223
But once you've understood how the programming works and you know how to search and find the answers 224
to your problems, then you'll be able to research through the code just as we're doing right now. If you 225
continue through this process of researching what each of these things do by using the documentation 226
from Apple, then you'll get a pretty good idea of what our code is doing right here. 227
We're basically grabbing hold of this C.wav file in our app resources right here, and then we're 228
making sure that our sound gets played even if the phone is on silent. 229
And then we tell our audio player that this is the file that we want to play C.wav, 230
and then we actually play it. And if there were any errors, then we actually catch those areas and print 231
it out. Now, this is a good time for a quick tip. 232
Now, when you search for things in the Apple Developer Documentation, you get the full documentation and 233
it is large. 234
Very often when I'm using something new that I've never come across before, I tend to try and read the 235
entire page on it and look through the links and try to get a overview of what I'm doing with my code. 236
But when you're just trying to look up things quickly to see what they do, 237
you can also simply hold down the option key on your keyboard and click on various things in your code. 238
So as soon as I've got my option key held down, I've got this crosshair that shows up, 239
and now if I hover over things such as my AVAudioPlayer or my Bundle, or AVudioSession, 240
so basically anything that's not programming, 241
so not the pink words which are to do with swift programming keywords, but the purple parts which come 242
from Apple's APIs, then we can click on it and it will show us the quick documentation. 243
So it's kind of like a shortened version of this. 244
It only contains the top part. And you can get a quick idea about what each part does or take a look 245
at it in detail in the developer docs. 246
So that's just a neat trick for you. 247
Now, we're finally ready to move on to the last step which is to customize your code. Now reading the 248
documentation can be quite a long and laborious process. But once you've implemented the code and gotten 249
it to work, then the documentation can be really helpful to help you figure out what each of these moving 250
parts are doing and what their roles are. 251
Once you've more or less understood what each line of code is, therefore, well, then it's time to make 252
it your own. 253
Because not everything that's in the code is necessary and the person who wrote the highest upvoted 254
answer is not Steve Jobs, right? 255
So they might also be wrong or they might be doing things that you don't actually need. 256
And this step is probably the hardest part yet because it requires a little bit more knowledge of Swift 257
programming and you'll be able to do this yourself once you've finished the course. 258
But for now, I'm going to vastly simplify the code, so that we deal with the harder programming concepts 259
after we've mastered the foundation parts. 260
If you open up the README file here, I want you to copy all the code that's inside the replacement 261
code, and go ahead and copy it and replace everything that's currently inside your ViewController with 262
this new code. 263
Now this, of course, relies on the fact that your IBAction was indeed called keyPressrf and it was spelled 264
exactly the same way. 265
Be sure to head into the IBAction and right-click on your button just to make sure that that is exactly 266
the same as this, 267
so that when you run your app, it doesn't crash, and we're going to simplify all of the code that we had 268
before 269
down to just these few lines. 270
Now, it's much simpler. 271
But we've gotten a little bit less functionality than before, 272
but it's fine for our needs. 273
We're still using the AVFoundation library from Apple. 274
We're still creating a new AVAudioPlayer, and then we're setting 275
our URL to be the location of our C.wav sound file in our project, and then we put this file 276
into our player just like loading up our CD player with a CD. 277
And finally, we tell it to play the sound. 278
Now, remember, because we took away the parts which allow our sound to be played when the phone is on 279
silent, 280
if you run this app right now and your phone is on silent on your physical device, then it will not make 281
a sound. 282
But as long as you switch it back onto normal, then it will be fine. And this is all of the code that 283
we got from our searching and our documentation reading, and we now have code that we understand, as well 284
as having implemented for our purposes. 285
Now, all that's left to do is to understand more of the Swift programming concepts behind this code, for 286
example, functions and what it's doing in our code. For all of that and more, I'll see you on the next lesson.