Beginning iPhone Development with Swift: Exploring the iOS SDK (2014)
Chapter 1. Welcome to the Swift Jungle
So, you want to write iPhone, iPod touch, and iPad applications? Well, we can’t say that we blame you. iOS—the core software of all of these devices—is an exciting platform that has been seeing explosive growth since it first came out in 2007. The rise of the mobile software platform means that people are using software everywhere they go. With the release of iOS 8, Xcode 6, and the latest incarnation of the iOS software development kit (SDK), things have only gotten better and more interesting.
What This Book Is
This book is a guide to help you get started down the path to creating your own iOS applications. Our goal is to get you past the initial difficulties to help you understand the way iOS applications work and how they are built.
As you work your way through this book, you will create a number of small applications, each designed to highlight specific iOS features and to show you how to control or interact with those features. If you combine the foundation you’ll gain through this book with your own creativity and determination, and then add in the extensive and well-written documentation provided by Apple, you’ll have everything you need to build your own professional iPhone and iPad applications.
Tip Dave, Jack, Jeff, and Fredrik have set up a forum for this book. It’s a great place to meet like-minded folks, get your questions answered, and even answer other people’s questions. The forum is at http://forum.learncocoa.org. Be sure to check it out!
What You Need
Before you can begin writing software for iOS, you’ll need a few items. For starters, you’ll need an Intel-based Macintosh running Mavericks (OS X 10.9) or Yosemite (OS X 10.10) or later. Any recent Intel-based Macintosh computer—laptop or desktop—should work just fine.
To get access to the latest and greatest from Apple, you’ll also really need to sign up to become a registered iOS developer. To create your developer account, just navigate to http://developer.apple.com/ios/. That will bring you to a page similar to the one shown in Figure 1-1.
Figure 1-1. Apple’s iOS Dev Center web site
First, click Log In. You’ll be prompted for your Apple ID. If you don’t have an Apple ID, click Register, create such an ID, and then log in. Once you are logged in, you’ll be taken to the main iOS development page. You’ll find links to a wealth of documentation, videos, sample code, and the like—all dedicated to teaching you the finer points of iOS application development.
The most important tool you’ll be using to develop iOS applications is called Xcode. Xcode is Apple’s integrated development environment (IDE). Xcode includes tools for creating and debugging source code, compiling applications, and performance-tuning the applications you’ve written.
You can download Xcode from the Mac App Store, which you can access from your Mac’s Apple menu.
SDK VERSIONS AND SOURCE CODE FOR THE EXAMPLES
As the versions of the SDK and Xcode evolve, the mechanism for downloading them has also been changing. For the past few years, Apple has been publishing the current “stable” version of Xcode and the iOS SDK on the Mac App Store, while simultaneously providing developers the ability to download preview versions of upcoming releases from its developer site. Bottom line: you usually want to download the latest released (non-beta) version of Xcode and the iOS SDK, so use the Mac App Store.
This book has been written to work with the latest versions of Xcode and the SDK. In some places, we have chosen to use new functions or methods introduced with iOS 8 that are not available in earlier versions of the SDK. We’ll be sure to point those situations out as they arise in this book.
Be sure to download the latest and greatest source code archive for examples from this book’s page at http://apress.com. We’ll update the code as new versions of the SDK are released, so be sure to check the site periodically.
The free Xcode download includes a simulator that will allow you to build and run iPhone and iPad apps on your Mac. This is perfect for learning how to program for iOS. However, the simulator does not support many hardware-dependent features, such as the accelerometer and camera. Also, the free option will not allow you to install your applications onto a real iPhone or other device, and it does not give you the ability to distribute your applications on Apple’s App Store. For those capabilities, you’ll need to sign up for one of the other options, which aren’t free:
· The Standard program costs $99/year. It provides a host of development tools and resources, technical support, distribution of your application via Apple’s App Store, and, most importantly, the ability to test and debug your code on an iOS device, rather than just in the simulator.
· The Enterprise program costs $299/year. It is designed for companies developing proprietary, in-house iOS applications.
For more details on these programs, visit http://developer.apple.com/programs/ios and http://developer.apple.com/programs/ios/enterprise to compare the two.
Because iOS supports an always-connected mobile device that uses other companies’ wireless infrastructures, Apple has needed to place far more restrictions on iOS developers than it ever has on Mac developers (who are able—at the moment, anyway—to write and distribute programs with absolutely no oversight or approval from Apple). Even though the iPod touch and the Wi-Fi-only versions of the iPad don’t use anyone else’s infrastructure, they’re still subject to these same restrictions.
Apple has not added restrictions to be mean, but rather as an attempt to minimize the chances of malicious or poorly written programs being distributed that could degrade performance on the shared network. Developing for iOS may appear to present a lot of hoops to jump through, but Apple has expended quite an effort to make the process as painless as possible. And also consider that $99 is still much less expensive than buying, for example, any of the paid versions of Visual Studio, which is Microsoft’s software development IDE.
This may seem obvious, but you’ll also need an iPhone, iPod touch, or iPad. While much of your code can be tested using the iOS simulator, not all programs can be. And even those that can run on the simulator really need to be thoroughly tested on an actual device before you ever consider releasing your application to the public.
Note If you are going to sign up for the Standard or Enterprise program, you should do it right now. The approval process can take a while, and you’ll need that approval to be able to run your applications on an actual device. Don’t worry, though, because while you are waiting, you can run all the projects in the first several chapters and the majority of the applications in this book on the iOS simulator.
What You Need to Know
This book assumes that you already have some programming knowledge. It assumes that you understand the fundamentals of programming in general and object-oriented programming in particular (you know what classes, objects, loops, and variables are, for example). However, we don’t assume that you are familiar with Swift, Apple’s new programming language. There’s an Appendix at the end of the book that introduces you to both Swift and the new Playground feature in Xcode that makes it easy to try out the features of this new and exciting language. If you’d like to learn more about Swift after reading the material in the Appendix, here are some useful sources of additional information:
· The Swift Programming Language is Apple’s own guide and reference for Swift. You can get it from the iBooks store or from the iOS developer site athttps://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/index.html.
· Swift Quick Syntax Reference by Matthew Campbell (Apress, 2014) is a code and syntax reference for the new language. See www.apress.com/9781484204405 for more details.
· If you have some prior experience with Objective-C, you can leverage it by reading Transitioning to Swift by Scott Gardner (Apress, 2014). See www.apress.com/9781484204078 for more information.
· Finally, if you’re an Android developer looking to see what life is like on the other side of the great divide, you might find Sean Liao’s Migrating to Swift from Android (Apress, 2014) helpful. Read more about it at www.apress.com/9781484204375.
You need to be familiar with iOS itself, as a user. Just as you would with any platform for which you wanted to write an application, get to know the nuances and quirks of the iPhone, iPad, or iPod touch. Take the time to get familiar with the iOS interface and with the way Apple’s iPhone and/or iPad applications look and feel.
What’s Different About Coding for iOS?
If you have never programmed in Cocoa or its predecessors NeXTSTEP or OpenStep, you may find Cocoa Touch—the application framework you’ll be using to write iOS applications—a little alien. It has some fundamental differences from other common application frameworks, such as those used when building .NET or Java applications. Don’t worry too much if you feel a little lost at first. Just keep plugging away at the exercises, and it will all start to fall into place after a while.
If you have written programs using Cocoa or NeXTSTEP, a lot in the iOS SDK will be familiar to you. A great many classes are unchanged from the versions that are used to develop for OS X. Even those that are different tend to follow the same basic principles and similar design patterns. However, several differences exist between Cocoa and Cocoa Touch.
Regardless of your background, you need to keep in mind some key differences between iOS development and desktop application development. These differences are discussed in the following sections.
Only One Active Application
On iOS, only one application can be active and displayed on the screen at any given time. Since iOS 4, applications have been able to run in the background after the user presses the Home button, but even that is limited to a narrow set of situations, and you must code for it specifically (you’ll see exactly how to do that in Chapter 15).
When your application isn’t active or running in the background, it doesn’t receive any attention whatsoever from the CPU, which will wreak havoc with open network connections and the like. iOS allows background processing, but making your apps play nicely in this situation will require some effort on your part.
Only One Window
Desktop and laptop operating systems allow many running programs to coexist, each with the ability to create and control multiple windows. However, unless you attach an external screen or use AirPlay, and your application is coded to handle more than one screen, iOS gives your application just one “window” to work with. All of your application’s interaction with the user takes place inside this one window, and its size is fixed at the size of the screen.
Programs on a desktop or laptop computer pretty much have access to everything the user who launched them does. However, iOS seriously restricts what your application can access.
You can read and write files only from the part of iOS’s file system that was created for your application. This area is called your application’s sandbox. Your sandbox is where your application will store documents, preferences, and every other kind of data it may need to retain.
Your application is also constrained in some other ways. You will not be able to access low-number network ports on iOS, for example, or do anything else that would typically require root or administrative access on a desktop computer.
Limited Response Time
Because of the way it is used, iOS needs to be snappy, and it expects the same of your application. When your program is launched, you need to get your application open, the preferences and data loaded, and the main view shown on the screen as fast as possible—in no more than a few seconds.
At any time when your program is running, it may have the rug pulled out from under it. If the user presses the Home button, iOS goes home, and you must quickly save everything before iOS suspends your application in the background. If you take longer than five seconds to save and give up control, your application process will be killed, regardless of whether you finished saving. There is an API that allows your app to ask for additional time to work when it’s about to go dark, but you’ve got to know how to use it.
Limited Screen Size
The iPhone’s screen is really nice. When introduced, it was the highest resolution screen available on a handheld consumer device, by far. But even today, the iPhone display isn’t all that big, and as a result, you have a lot less room to work with than on modern computers. The screen was just 320 × 480 on the first few iPhone generations, and it was later doubled in both directions to 640 × 960 with the introduction of the iPhone 4’s Retina display. Today, the screen of the largest iPhone (the iPhone 6 Plus) measures 1080 × 1920 pixels. That sounds like a decent number of pixels, but keep in mind that these high-density displays (for which Apple uses the term “Retina”) are crammed into pretty small form factors, which has a big impact on the kinds of applications and interactivity you can offer on an iPhone and even an iPad. Table 1-1 lists the sizes of the screens of all of the devices that are supported by iOS 8 at the time of writing.
Table 1-1. iOS Device Screen Sizes
The hardware size is the actual physical size of the screen in pixels. However, when writing software, the size that really matters is the one in the Software Size column. As you can see, in most cases, the software size is only half that of the actual hardware. This situation came about when Apple introduced the first Retina device, which had twice as many pixels in each direction as its predecessor. If Apple had done nothing special, all existing applications would have been drawn at half-scale on the new Retina screen, which would have made them unusable. So Apple chose to internally scale everything that applications draw by a factor of 2, so that they would fill the new screen without any code changes. This internal scaling by a factor of 2 applies to all devices with a Retina display, apart from the iPhone 6 Plus, which has a higher-density screen that requires a scaling factor of 3. For the most part, though, you don’t need to worry too much about the fact that your application is being scaled—all you need to do is work within the software screen size and iOS will do the rest.
The only exceptions to this rule are bitmap images. Since bitmap images are, by their nature, fixed in size, for best results you can’t really use the same image on a Retina screen as you would on a non-Retina screen. If you try to do that, you’ll see that iOS scales your image up for a device that has a Retina screen, which has the effect of introducing blur. You can fix this by including separate copies of each image for the 2x and 3x Retina screens, and iOS will pick the version that matches the screen of the device on which your application is running.
Note If you look back at Table 1-1, you’ll see that it appears that the scale factor in the fourth column is the same as the ratio of the hardware size to the software size. For example, on the iPhone 6, the hardware width is 750 and software width is 375, a ratio of 2:1. Look carefully, though, and you’ll see that there’s something different about the iPhone 6 Plus. The ratio of the hardware width to the software width is 1080/414, which is 2.608:1, and the same applies to the height ratio. So in terms of the hardware, the iPhone 6 Plus does not have a truly 3x Retina display. However, as far as the software is concerned, a 3x scale is used, which means that an application written to use the software screen size of 414 × 736 is first logically mapped to a virtual screen size of 1242 × 2208 and the result is then scaled down a little to match the actual hardware size of 1080 × 1920. Fortunately, this doesn’t require you to do anything special because iOS takes care of all the details.
Limited System Resources
Any old-time programmers who are reading this are likely laughing at the idea of a machine with at least 512MB of RAM and 16GB of storage being in any way resource-constrained, but it is true. Developing for iOS is not, perhaps, in exactly the same league as trying to write a complex spreadsheet application on a machine with 48KB of memory. But given the graphical nature of iOS and all it is capable of doing, running out of memory is very easy.
The iOS devices available right now have either 512MB (iPhone 4S, iPad 2, the original iPad mini, the latest iPod touch), or 1024MB of physical RAM (iPhone 5c, iPhone 5s, iPhone 6, iPhone 6 Plus, iPad Air, iPad mini Retina), though this will likely increase over time. Some of that memory is used for the screen buffer and by other system processes. Usually, no more than half of that memory is left for your application to use, and the amount can be considerably less, especially now that other apps can be running in the background.
Although that may sound like it leaves a pretty decent amount of memory for such a small computer, there is another factor to consider when it comes to memory on iOS. Modern computer operating systems like OS X will take chunks of memory that aren’t being used and write them out to disk in something called a swap file. The swap file allows applications to keep running, even when they have requested more memory than is actually available on the computer. iOS, however, will not write volatile memory, such as application data, out to a swap file. As a result, the amount of memory available to your application is constrained by the amount of unused physical memory in the iOS device.
Cocoa Touch has built-in mechanisms for letting your application know that memory is getting low. When that happens, your application must free up unneeded memory or risk being forced to quit.
Some New Stuff
Since we’ve mentioned that Cocoa Touch is missing some features that Cocoa has, it seems only fair to mention that the iOS SDK contains some functionality that is not currently present in Cocoa—or, at least, is not available on every Mac:
· The iOS SDK provides a way for your application to determine the iOS device’s current geographic coordinates using Core Location.
· Most iOS devices have built-in cameras and photo libraries, and the SDK provides mechanisms that allow your application to access both.
· iOS devices have built-in motion sensors that let you detect how your device is being held and moved.
A Different Approach
Two things iOS devices don’t have are a physical keyboard and a mouse, which means you have a fundamentally different way of interacting with the user than you do when programming for a general-purpose computer. Fortunately, most of that interaction is handled for you. For example, if you add a text field to your application, iOS knows to bring up a keyboard when the user touches that field, without you needing to write any extra code.
Note All iOS devices allow you to connect an external keyboard via Bluetooth, which gives you a nice keyboard experience and saves some screen real estate. Connecting a mouse is not an option.
What’s in This Book
Here is a brief overview of the remaining chapters in this book:
· In Chapter 2, you’ll learn how to use Xcode’s partner in crime, Interface Builder, to create a simple interface, placing some text on the screen.
· In Chapter 3, you’ll start interacting with the user, building a simple application that dynamically updates displayed text at runtime based on buttons the user presses.
· Chapter 4 will build on Chapter 3 by introducing you to several more of iOS’s standard user-interface controls. We’ll also demonstrate how to use alerts and action sheets to prompt users to make a decision or to inform them that something out of the ordinary has occurred.
· In Chapter 5, we’ll look at handling rotation and Auto Layout, the mechanisms that allow iOS applications to be used in both portrait and landscape modes.
· In Chapter 6, we’ll move into more advanced user interfaces and explore creating applications that support multiple views. We’ll show you how to change which view is shown to the user at runtime, which will greatly enhance the potential of your apps.
· Tab bars and pickers are part of the standard iOS user interface. In Chapter 7, we’ll look at how to implement these interface elements.
· In Chapter 8, we’ll cover table views, the primary way of providing lists of data to the user and the foundation of hierarchical navigation–based applications. You’ll also see how to let the user search your application data.
· One of the most common iOS application interfaces is the hierarchical list that lets you drill down to see more data or more details. In Chapter 9, you’ll learn what’s involved in implementing this standard type of interface.
· From the beginning, all sorts of iOS applications have used table views to display dynamic, vertically scrolling lists of components. More recently, Apple introduced a new class called UICollectionView that takes this concept a few steps further, giving developers lots of new flexibility in laying out visual components. Chapter 10 will get you up and running with collection views.
· In Chapter 11, we’ll show you how to build master-detail applications, which present a list of items (such as the emails in a mailbox) and let the user view the details of each individual item, one at a time. You’ll also see how to use the iOS controls that support this way of working, which were originally developed for the iPad and are now also available on the iPhone.
· In Chapter 12, we’ll look at implementing application settings, which is iOS’s mechanism for letting users set their application-level preferences.
· Chapter 13 covers data management on iOS. We’ll talk about creating objects to hold application data and see how that data can be persisted to iOS’s file system. We’ll also discuss the basics of using Core Data, which allows you to save and retrieve data easily.
· In iOS 5, Apple introduced iCloud, which allows your document to store data online and sync it between different instances of the application. Chapter 14 shows you how to get started with iCloud.
· iOS developers have access to a powerful library that simplifies multithreaded development called Grand Central Dispatch, or GCD for short. In Chapter 15, we’ll introduce you to Grand Central Dispatch and also show you how to use the iOS features that allow you, under certain circumstances, to run your application in the background.
· Everyone loves to draw, so we’ll look at doing some custom drawing in Chapter 16, where we’ll introduce you to the Core Graphics system.
· In iOS 7, Apple has introduced a new framework called Sprite Kit for creating 2D games. It includes a physics engine and animation systems, and works for making OS X games, too. You’ll see how to make a simple game with Sprite Kit in Chapter 17.
· The multitouch screen common to all iOS devices can accept a wide variety of gestural inputs from the user. In Chapter 18, you’ll learn all about detecting basic gestures, such as the pinch and swipe. We’ll also look at the process of defining new gestures and talk about when new gestures are appropriate.
· iOS is capable of determining its latitude and longitude thanks to Core Location. In Chapter 19, we’ll build some code that uses Core Location to figure out where in the world your device is and use that information in our quest for world dominance.
· In Chapter 20, we’ll look at interfacing with iOS’s accelerometer and gyroscope, which is how your device knows which way it’s being held, the speed and direction in which it is moving, and where in the world it’s located. We’ll also explore some of the fun things your application can do with that information.
· Nearly every iOS device has a camera and a library of pictures, both of which are available to your application, if you ask nicely! In Chapter 21, we’ll show you how to ask nicely.
· iOS devices are currently available in more than 90 countries. In Chapter 22, we’ll show you how to write your applications in such a way that all parts can be easily translated into other languages. This helps expand the potential audience for your applications.
· Finally, there’s an Appendix that introduces the Swift programming language and covers all of the features that you’ll need to know to understand the example code in this book.
What’s New in This Update?
Since the first edition of this book hit the bookstores, the growth of the iOS development community has been phenomenal. The SDK has continually evolved, with Apple releasing a steady stream of SDK updates. Well, we’ve been busy, too! Both iOS 8 itself and Xcode 6 contain a lot of new enhancements. We’ve been hard at work updating the book to cover the new technologies in both iOS 8and Xcode 6 that you’ll need to be aware of to start writing iOS applications. We’ve rebuilt every project from scratch to ensure not only that the code compiles using the latest version of Xcode and the iOS SDK, but also that each one takes advantage of the latest and greatest features offered by Cocoa Touch. We’ve also made a ton of subtle changes throughout the book and, of course, we’ve reshot every screenshot.
Swift and Xcode Versions
Swift is so new that it is still in a state of flux. At the time of writing, even though iOS 8 has been officially released, Apple is still making changes to the way that Swift imports iOS APIs. As a result, it is possible that example code that compiles and works with the version of Xcode with which it was tested no longer works by the time you read this book. Interestingly, Apple has promised that the compiled binaries for applications written now will work on later versions of iOS, but it is not guaranteed that the source code for those same applications will continue to compile. The code in this book was tested with Xcode 6.1. If you find that some of the code no longer compiles with the release of Xcode that you are using, please visit the book’s page at Apress.com and download the latest source code. If after doing this you are having problems, please bring it to our attention by submitting an Erratum at Apress.com.
Are You Ready?
iOS is an incredible computing platform and an exciting new frontier for your development pleasure. Programming for iOS is going to be a new experience—different from working on any other platform. For everything that looks familiar, there will be something alien—but as you work through the book’s code, the concepts should all come together and start to make sense.
Keep in mind that the examples in this book are not simply a checklist that, when completed, magically grant you iOS developer guru status. Make sure you understand what you did and why before moving on to the next project. Don’t be afraid to make changes to the code. Observing the results of your experimentation is one of the best ways you can wrap your head around the complexities of coding in an environment like Cocoa Touch.
That said, if you have your iOS SDK installed, turn the page. If not, get to it! Got it? Good. Then let’s go!