Chapters

Hide chapters

iOS Apprentice

Eighth Edition · iOS 13 · Swift 5.2 · Xcode 11

Before You Begin

Section 0: 3 chapters
Show chapters Hide chapters

Checklists

Section 2: 12 chapters
Show chapters Hide chapters

My Locations

Section 3: 11 chapters
Show chapters Hide chapters

Store Search

Section 4: 12 chapters
Show chapters Hide chapters

1. Introduction
Written by Joey deVilla

Hello there, and welcome to iOS Apprentice: Beginning iOS Development with Swift, Eighth Edition, the swiftest way — if you’ll pardon the pun — to iOS development mastery!

With this book as your guide, you’ll learn how to make your own iPhone and iPad apps using Apple’s Swift programming language, the Xcode 11 integrated development environment and the UIKit and SwiftUI user interface frameworks.

You’ll learn by doing, and you’ll do so through building six interesting iOS apps. In the process, you’ll discover how to use programming to harness features built into iOS and iOS devices and combine them into apps.

The apps you’ll make in The iOS Apprentice
The apps you’ll make in The iOS Apprentice

Learning should be fun, which is why you’ll start your journey by building a simple but fun iPhone game named Bullseye that will teach you the basics of iPhone programming. Each of the app that follow will introduce you to new programming techniques and iOS features, building upon what you’ve learned.

Taken together, the six apps that you’ll build will give you a solid foundation of knowledge — enough to make your own apps. By the end of the book, you’ll be experienced enough to turn your ideas into real apps that you can put on the App Store!

If you’ve never programmed before or you’re new to iOS, don’t worry. You should be able to follow along with the step-by-step instructions and understand how to make these apps. Each chapter has a ton of illustrations to keep you from getting lost. Not everything will make sense right away, but hang in there and all will become clear in time.

Writing your own iOS apps is a lot of fun, but it’s also hard work. If you have the imagination and perseverance, there’s no limit to what you can make your apps do. It’s my sincere belief that this book can turn you from a complete newbie into an accomplished iOS developer, but you do have to put in the time and effort. By writing this book, Eli and I have done our parts. The rest is up to you…

About this book

iOS Apprentice will help you become an excellent iOS developer, but only if you let it. Here are some tips that will help you get the most out of this book.

Learn through repetition

You’re going to make several apps in this book. Even though the apps are quite simple, you may find the instructions hard to follow at first — especially if you’ve never done any computer programming before. You’ll be facing a lot of new concepts.

It’s okay if you don’t understand every last detail right away, as long as you get the general idea. As you proceed through the book, you’ll go over many of those concepts again and again until they solidify in your mind.

Follow the instructions yourself

It’s important that you not just read the instructions, but also actually follow them. Open Xcode, type in the source code fragments and run the app in the simulator as instructed. This helps you to see how the app develops, step by step.

Even better, play around with the code and with the Xcode settings. Feel free to modify any part of the app and see what the results are. Make a small change to the code and see how it affects how the app runs. Experiment and learn! Don’t worry about breaking stuff — that’s half the fun. You can always find your way back to the beginning. You might even learn something from simply breaking the code and learning how to fix it.

If you try everything but are still stuck, drop by the forums for this book at forums.raywenderlich.com. The team behind this book monitors the forum and will be happy to answer any questions related to the book and issues you might have run into.

Don’t panic — bugs happen!

You’ll run into problems, guaranteed. Your programs will have strange bugs that will leave you stumped. Trust me, I’ve been programming for more years than I care to admit and that still happens to me, too. We’re only humans and our brains have a limited capacity to deal with complex programming problems. In this book, I’ll give you tools for your mental toolbox that will allow you to find your way out of any hole you’ve dug for yourself.

Understanding beats copy-pasting

Too many people attempt to learn programming by blindly copying and pasting code that they find on blogs and other websites, without really knowing what that code does or how it should fit into their programs.

There’s nothing wrong with looking on the web for solutions — I do it all the time, for both work and hobby projects — but I want to give you the tools and knowledge to understand what you’re doing and why. That way, you’ll learn more quickly and write better programs.

This is hands-on, practical advice, not a bunch of dry theory (although we can’t avoid some theory). You’re going to build real apps right from the start, and I’ll explain how everything works along the way, with lots of images to illustrate what is going on.

I’ll do my best to make it clear how everything fits together, why we do things a certain way and what the alternatives are.

Do the exercises

I’ll also ask you to do some thinking of your own — yes, there are exercises! It’s in your best interest to actually do these exercises. There’s a big difference between knowing the path and walking the path… And the only way to learn programming is to do it.

I encourage you to not just do the exercises but also to play with the code you’ll be writing. Experiment, make changes and try to add new features. Software is a complex piece of machinery and to find out how it works, you have to tinker, take it apart and put it back together — and sometimes in new and interesting ways. That’s how you learn!

Have fun!

Last but not least, remember to have fun! Step by step, you’ll build your understanding of programming while making fun apps. By the end of this book, you’ll have learned the essentials of Swift, the iOS Software Development Kit (SDK) and both the UIKit and the SwiftUI frameworks. More importantly, you should have a pretty good idea of how everything goes together and how to think like a programmer.

This book has one ultimate goal: That by the time you reach the end, you’ll have learned enough to stand on your own two feet as a developer. We’re confident that, eventually, you’ll be able to write any iOS app that you want as long as you understand the basics. You still may have a lot to learn but, when you’re through with iOS Apprentice, you’ll be able to do it without the training wheels.

Is this book right for you?

Whether you’re completely new to programming or you come from a different programming background and want to learn iOS development, this book is for you!

If you’re a complete beginner, don’t worry — this book doesn’t assume you know anything about programming or making apps. Of course, if you do have programming experience, that will help. Swift is a relatively new programming language but, in many ways, it’s similar to other popular languages such as Python, C# or JavaScript.

If you’ve tried iOS development before with the old language, Objective-C, its low-level nature and strange syntax may have put you off. I have good news for you: Now that we have a modern language in Swift, iOS development has become a lot easier to pick up.

This book can’t teach you all the ins and outs of iOS development. The iOS SDK is huge and grows with each new release, so there’s no way we can cover everything. Fortunately, we don’t need to. You just need to master the essential building blocks of Swift and the iOS SDK. Once you understand these fundamentals, you can easily figure out how the other parts of the SDK work and learn the rest on your own terms.

The most important thing I’ll teach you is how to think like a programmer. That will help you approach any programming task, whether it’s a game, a utility, a mobile app that connects to web services or anything else you can imagine.

As a programmer, you’ll often have to think your way through difficult computational problems and find creative solutions. By methodically analyzing these problems, you’ll be able to solve them, no matter how complex. Once you possess this valuable skill, you can program anything!

iOS 13 and later only

The code in this book is written exclusively for iOS version 13 and later. Each new release of iOS is such a big departure from the previous one that it doesn’t make sense to keep developing for older devices and iOS versions. Things move quickly in the world of mobile computing!

Most iPhone, iPod touch and iPad users are quick to upgrade to the latest version of iOS, so you don’t need to be too worried that you’re leaving potential users behind.

Owners of older devices may be stuck with older iOS versions, but they make up a tiny portion of the market. The cost of supporting these older iOS versions for your apps is usually greater than the handful of extra customers it brings you.

It’s ultimately up to you to decide whether it’s worth making your app available to users with older devices, but my recommendation is that you focus your efforts where they matter most. Apple, as a company, relentlessly looks towards the future — if you want to play in Apple’s back yard, it’s wise to follow its lead. So back to the future it is!

What you need

It’s a lot of fun to develop for the iPhone and iPad but, like most hobbies (or businesses!), it will cost some money. Of course, once you get good at it and build an awesome app, you’ll have the potential to make that money back many times.

In order to get started, you’ll need to invest in a couple of things.

You’ll need a Mac computer with an Intel processor. Any Mac that you’ve bought in the last few years will do, even a Mac mini or MacBook Air.

Programming is one of those computing tasks that uses a lot of RAM. The Mac you use for the exercises in this book should have at least 8GB of RAM. These days, even the lowest-end Mac in the Apple Store comes with that amount, and having more RAM will improve your developer experience even better. Keep this general rule in mind: The more RAM, the better. A smart developer invests in good tools!

With some workarounds, it’s possible to develop iOS apps on a Windows or a Linux machine, or on a regular PC that has macOS installed (a “Hackintosh”). If you’re up for a challenge, you can try iOS development on these machines, but you’ll save yourself a lot of time and hassle by just getting a Mac.

If you can’t afford to buy one of the current Macs, consider getting a refurbished one from Apple or buying second-hand. It should be a Mac that dates from mid-2012 or later; just make sure it meets the minimum requirements (Intel CPU, preferably with at least 8 GB RAM). If it helps, you should know that I use a mid-2014 MacBook Pro with 16GB of RAM at my job, where I write apps for a living.

Your Mac needs to have at least macOS 10.14.4 Mojave, and I strongly recommend that you use macOS 10.15 Catalina, especially when building apps with SwiftUI, which you’ll do in the later sections of this book.

I strongly recommend having an iPhone, iPad or iPod touch running iOS 13. I’m assuming that you have at least one of these. iOS 13 runs on the following devices:

  • iPhone 6s or newer
  • iPad Pro (any generation)
  • iPad 5th generation or newer
  • iPad Air 2 or 3rd generation
  • iPad Mini 5th generation
  • iPod Touch 7th generation

If you have an older device, then this is a good time to think about getting an upgrade. But don’t worry if you don’t have a suitable device: You can do most of your testing on iOS Simulator.

Note: Even though this book is about developing apps for the iPhone, everything within applies equally to the iPad and iPod touch. Aside from small hardware differences, these devices use iOS or its close cousin iPadOS and you program them in exactly the same way. You should also be able to run the apps from this book on your iPad or iPod touch without problems.

Eventually, you’ll need an Apple Developer Program account: You can download all the development tools for free and you can try out your apps on your own iPhone, iPad or iPod touch while you’re developing, so you don’t have to join the Apple Developer Program just yet. When you get to the point where you’re ready to submit apps to the App Store, you’ll have to enroll in the paid Developer Program. This will cost you $99 per year.

See developer.apple.com/programs/ for more info.

Xcode

The first order of business is to download and install Xcode and the iOS SDK.

Xcode is the development tool for iOS apps. It has a text editor where you’ll enter the source code that defines what your app does and a visual editor where you’ll design your app’s user interface.

Xcode has a compiler, which is software that transforms the source code that you write into an an app that can run in the iOS Simulator or on your iPhone. Because no app is bug-free, Xcode also has a debugger that helps you find defects in your code. Unfortunately, it won’t automatically fix them for you; that’s something you still have to do yourself.

You can download Xcode for free from the Mac App Store (apple.co/2wzi1L9). Before you do so, I strongly recommend that you first upgrade to the latest version of macOS, which is also available for free from the Mac App Store. Get ready for a big download, as the full Xcode package is almost 8 GB.

Important: You may already have a version of Xcode on your system that came pre-installed with your version of macOS. That version could be hopelessly outdated, so don’t use it. Apple puts out new releases on a regular basis and you always want to develop with the latest Xcode and the latest available SDK on the latest version of macOS.

This revision of the book was written using Xcode version 11 and the iOS 13 SDK on macOS Catalina (10.15). By the time you read this, the version numbers might have gone up again.

We’ll do our best to keep the PDF versions of the book up-to-date with new releases of the development tools and iOS versions, but don’t panic if the screenshots don’t correspond 100% to what you see on your screen. In most cases, the differences will be minor.

Many older books and blog posts (anything before 2014) talk about iOS development in Xcode 5 or earlier. Ignore them; they’re from an earlier era of iOS development and use a completely different programming language. If you’re look at an article or book that predates Swift, it’s seriously out of date.

More recent materials may mention Xcode versions 6 through 10. There are similar to Xcode 11 but differ in many of the details. Xcode 11 is the first version to include the new SwiftUI framework, and you won’t find anything about it in older tutorials.

If you’re reading an article and you see a picture of Xcode that looks different from yours, it might be written for an older version. You may still be able to get something out of those articles, as the programming examples are still valid. It’s just Xcode that is slightly different.

What’s ahead: An overview

The iOS Apprentice is spread across six apps, and moves from beginning to intermediate topics. You’ll build each app from start to finish, from scratch!

Let’s take a look at what’s ahead.

Building apps with UIKit and SwiftUI

There’s a saying (erroneously) attributed to the Chinese: “May you live in interesting times.” Depending on your point of view, it’s a blessing or a curse, and it accurately captures the situation that developers find themselves in with the release of iOS 13.

From the very first iPhone OS and all the way up to iOS 12, iOS apps were written using the iPhone’s original user interface framework, UIKit. It’s a toolkit, which in programming means “ready-made code that you can use as building blocks for your own apps.”

UIKit is based on an even older toolkit, AppKit, which has been used for building user interfaces for macOS desktop apps since the very first version back in 2001. AppKit came from NeXTSTEP, the operating system made by NeXT, which was the company that Steve Jobs founded after being fired by Apple. Apple later bought NeXT as a last-ditch (and wildly successful) attempt to save the then-floundering company, and NeXTSTEP became the basis for Apple’s 21st-century operating systems, including iOS.

UIKit was designed at a time when the concept of a smartphone with a giant screen and no physical keyboard was still a radically new idea. Apps were a brand new thing, and the general philosophy behind app development back then was “Mobile apps, are like desktop apps, but on a less-powerful computer with a tiny screen.” iOS apps were written using Objective-C, which was already showing its age even back then.

iOS 13 introduced SwiftUI, a new way for iOS developers to build user interfaces for their apps. It was designed SwiftUI was designed to reflect the way apps are written today and to make it easier to port your iOS apps to Apple’s other platforms: macOS, watchOS and tvOS. It’s also tightly integrated with the now-preferred programming language for iOS apps: Swift.

SwiftUI is so new that outside of Apple, there aren’t that many experts on it. For the next little while, most iOS apps and most of the iOS code examples you’ll find will be based on UIKit.

The near future will be interesting for iOS developers because they’ll need to be familiar with both toolkits. That’s why this book covers UIKit and SwiftUI.

Learn UIKit, then SwiftUI

Even though it’s “the old way,” you’ll learn how to build iOS apps using UIKIt first. There are a number of reasons for this approach.

First, UIKit won’t just disappear. Theres over a decade’s worth of UIKit-based code, documentation and tutorials out there, and most iOS apps are based on UIKit. Right now, the overwhelming majority of iOS apps and their code are based on UIKit. Based on how slowly many people upgrade their systems and software — remember, there are still hundreds of millions of computers still running Windows 7 — you should expect UIKit to be around for the next little while. We’re in the early days of the transition from UIKit to SwiftUI, which means that you’ll need to be familiar with both frameworks for at least the next couple of iOS versions.

Second, if you’re new to iOS programming, and especially if you’re new to programming in general, you’ll find that it’s much easier to start with building apps based on UIKit. While SwiftUI appears to be the framework that we’ll all use in the future, you need to understand a surprisingly large number of programming concepts in order to use it effectively. It’s much easier to start with UIKIt while learning the findamentals of iOS programming and then graduate to SwiftUI once you’ve written a few apps.

Third, there’s the fact the SwiftUI has only just been released and has many “rough edges”. This isn’t surprising for a brand new framework, especially one that seems to have been rushed to market. In contrast, Apple has polished UIKit over the years, fixing bugs and making improvements in response to feedback from developers. When you’re learning how to program, you don’t want to be fighting the framework at the same time.

Finally, there’s the community of over 20 million iOS developers. You’ll probably end up talking with them about iOS development, ask them questions and maybe even collobrate with some of them on a project. Most of their iOS devlopment experience will be based on building UIKit apps, which means you’ll need to be familiar with UIKIt.

For these reasons, you’ll start by building four apps “the old way” — using the UIKit framework. In the process, you’ll learn both the fundamentals of software development and cover enough iOS programming topics to write a variety of apps. With that experience, you’ll be prepared for the transition to “the new way”, which you’ll make be rewriting the first two apps using SwiftUI.

Here are the apps you’ll write…

App 1: Bullseye

Your first app will be Bullseye, a game that challenges the user to move a slider to a precise position without any help. Even though it’s a simple app, you’ll learn a lot while building it: How to use Xcode, building user interfaces using Storyboards, responding to user actions, performing calculations, navigating between screens, and adding professional touches to an app.

App 2: Checklists

For your next trick, you’ll create Checklists, a to-do list app. You’ll learn how to use table views in order to present lists of items to the user, use navigation controllers to organize your app’s screens in a hierarchical fashion, share information between objects, save the user’s data so that it doesn’t disappear when they shut down the app or the phone and use local notifications to provide timely reminders of checklist items whose deadlines are fast approaching. Now you’re making apps for real!

App 3: MyLocations

For your third app, you’ll develop MyLocations, an app that lets you keep track of the places you’ve been and find interesting. It will use the built-in GPS to get the current location, store these locations in a database, display them on a map, and use the camera to attach photos to locations. These are features that many apps use, so be sure not to skip this exercise.

App 4: StoreSearch

Mobile apps often need to talk to web services, and that’s what you’ll do in StoreSearch. It’s a stylish app that lets you search for products on the iTunes Store. In building this app, you’ll learn the basics of networking — that is, having your app get information from another computer, namely the iTunes Store server. You’ll also be introduced to version control, which is like Apple’s Time Machine, but for your code!

Apps 5 and 6: Bullseye and Checklists in SwiftUI

Your introduction to Apple’s new app framework will give you a sense of deja vu, because you’ll rewrite this book’s first two apps, Bullseye and Checklists, using SwiftUI. The programming concepts and constructs that you learned writing apps with UIKIt will serve you well as you learn a whole new way to write apps.

Let’s get started and turn you into a full-fledged iOS developer!

The language of the computer

The iPhone may pretend that it’s a phone, but it’s really a pretty advanced handheld computer that happens to have the ability to make phone calls. Like any computer, the iPhone works by performing calculations with ones and zeros. When you write software to run on the iPhone, you somehow have to translate the ideas in your head into those ones and zeros so that the computer can understand you.

Fortunately, you don’t have to write any ones and zeros yourself. That would be a bit too much to ask of the human brain. On the other hand, everyday English — or any other natural human language — just isn’t precise enough to tell a computer what to do.

Instead of ones and zeros, you’ll use an intermediary language: Swift. It’s a little bit like English, and reasonably straightforward for us humans to understand. At the same time, it’s ordered and structured enough so that it can be easily translated into something the computer can understand as well.

This is an approximation of the language that the computer speaks:

Actually, what the computer sees is this:

movl and calll are instructions that the computer follows. They’re part of what’s called assembly language, which is an abstraction that makes machine code more readable for humans. I don’t know about you, but for me, it’s still hard to make much sense out of it.

It certainly is possible to write programs in that arcane language. In the days of 8- and 16-bit computers, if you were writing a videogame or some other app that had to eke the most performance out of those slow machines, you had to. Even today, programmers who need to work at the system level or need maximum performance from minimal hardware will write some assembly language. I’ll take having my apps run fractions of a second slower if I can write programs that I can follow because they look like this:

func handleMusicEvent(command: Int, noteNumber: Int, velocity: Int) {

  if command == NoteOn && velocity != 0 {
    playNote(noteNumber + transpose, velocityCurve[velocity] / 127)

  } else if command == NoteOff ||
            (command == NoteOn && velocity == 0) {
    stopNote(noteNumber + transpose, velocityCurve[velocity] / 127)

  } else if command == ControlChange {
    if noteNumber == 64 {
      damperPedal(velocity)
    }
  }
}

The above code snippet is from a sound synthesizer program. Even if you’ve never programmed before, you can sort of figure out what’s going on. It’s almost English.

The Swift programming language debuted in 2014 at Apple’s World Wide Developers Conference to great applause. Since then, it has become of the most popular programming languages, according to developer surveys and web sites that track which languages programmers use. It supports the object-oriented and functional programming paradigms that most programmers are familiar with, and it also introduces a new one: Protocol-oriented programming. Fortunately, it has many things in common with other popular programming languages, so if you’re already familiar with C#, Python, Ruby or JavaScript, you’ll feel right at home with Swift.

Swift isn’t the only option for making apps. Until recently, most iOS apps were programmed in Objective-C, which first appeared in 1984. Objective-C is an object-oriented extension of the tried-and-true C programming language, which was first released in 1972. Objective-C comes with a lot of ’70s and ’80s baggage and doesn’t have a lot of the niceties that modern developers have come to expect. That’s why Apple created a new language.

Objective-C will still be around for a while, but the future of iOS development is Swift. All the cool kids are using it already.

C++ is another language that adds object-oriented programming to C. It’s very powerful but, as a beginning programmer, you probably want to stay away from it. I only mention it because you can also use C++ to write iOS apps. There’s also an unholy marriage of C++ and Objective-C named Objective-C++ that you may come across from time to time. If you see it, back away slowly and don’t make eye contact.

I could have started The iOS Apprentice with an in-depth exploration of the features of Swift, but this is a tutorial, not a sedative! So, instead, I’ll follow the adage of “Show, don’t tell” and explain the language as we go along, very briefly at first, but in more depth later.

In the beginning, the general concepts — what is a variable, what is an object, how do you call a method, and so on — are more important than the details. Slowly but surely, all the arcane secrets of the Swift language will be revealed to you!

Are you ready to begin writing your first iOS app?

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.