Swift™ iOS 24-Hour Trainer
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2016 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-119-07355-0
ISBN: 978-1-119-07346-8 (ebk)
ISBN: 978-1-119-07342-0 (ebk)
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions
.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com
. For more information about Wiley products, visit www.wiley.com
.
Library of Congress Control Number: 2015957030
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Swift is a trademark of Apple, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.
Abhishek Mishra has been developing software for over 18 years and has experience with a diverse set of programming languages and platforms. He is the author of iPhone and iPad App 24-Hour Trainer and the technical reviewer of Professional iOS Programming. He holds a Master's degree in Computer Science from the University of London and is a freelance consultant and trainer specializing in mobile application development. His clients include British Sky Broadcasting, Centrica PLC, Expedia Inc., Kantar Media, and Havas Media. He lives with his wife and daughter in London.
Chaim Krause is a Simulation Specialist for the U.S. Army. One of his responsibilities is to develop small games for use at the Army University. Chaim has been developing software for about 30 years, progressing through BASIC, Delphi/Pascal, C++, Java, Objective-C, and C# on platforms from the TRS-80 through Windows, OS X, Android, and iOS. He has also worked with Arduinos. Chaim has been the Technical Editor for a dozen books on topics as varied as iPhone/iPad, Android, iWatch, Arduino, and Unity. When not working in front of a computer at his day job, Chaim is often sitting in front of a computer at home playing wargames or developing his own game. Chaim can be reached at chaim@chaim.com.
This book would not have been possible without the support of the team at John Wiley and Sons—Aaron Black, Christina Haviland, Nancy Rapoport, and Mariann Barsolo. I would also like to thank Chaim Krause for taking the time to read the entire manuscript and his keen eye for detail. It has been my privilege to work with you. Thank you.
When I first began learning iOS development, I started out like most developers, from the humble Hello World application. I was overwhelmed with new concepts, such as view controllers and table views. My background with C++ did not help much when it came to working with Objective-C, and I had to start from scratch. There was no book written on the subject and everything had to be learned from Apple's documentation and personal blogs.
Eventually I came to grips with Objective-C, and with practice, I grew more proficient. With the launch of iOS 7, Apple announced a new language called Swift, and it felt almost like going back to square one again, as I learned how to perform familiar tasks with a new language.
This book is written to help someone new to iOS development learn the basic concepts and (I hope) avoid making the mistakes I made when starting out myself. That being said, this book should also be useful for an experienced Objective-C developer who is looking to transition over to Swift. This book adopts a hands-on Try It approach, and you get to try out each new concept as you progress through the book.
iOS application development is a huge topic, and it is just not possible to include every single topic related to iOS application development in this book. When selecting topics to include in this book, I have tried to strike a balance between the absolute basics and more advanced topics such as Test Driven Development, CloudKit, and UI testing.
This book has been written for you, the reader. I hope that after reading this book, you can take your first steps into the wildly exciting world of iOS App development.
This book is for beginners with little programming experience who want to pursue a career in the exciting world of iOS development. It is also for experienced Objective-C developers who want to learn Swift programming.
Although you do not need to have any prior programming experience, a little knowledge will help you move faster through the initial lessons, particularly the basics of object-oriented software development. If you are a more experienced developer, then this book can help you get up-to-speed with new concepts relating specifically to iOS 9 development and Swift.
This book covers iOS 9 application development with Swift 2. That includes development for both the iPhone and the iPad. The lessons in this book use XCode 7.0 and make use of new Swift features such as the
clause. All of the lessons use storyboards to construct user interfaces.guard let
The book starts off with an introduction to the Swift language followed by lessons that will teach you how to perform common tasks such as displaying alerts, pickers, and collection views. Toward the end of the book, you will find slightly more advanced topics such as iCloud document storage, CloudKit, Test Driven Development, and UI testing.
The appendixes cover ways to test and deploy your apps, ranging from deploying a build to your personal device to distributing your app to beta testers via TestFlight.
This book consists of 33 short lessons and 3 appendixes. Each lesson introduces a single topic and ends with a step-by-step Try It section where you get to apply the concepts you've learned in the lesson to create a simple iOS application. The source code for the Try It exercises is available for download at
. Lessons toward the beginning of the book are simpler and progress in complexity as you work your way through the book.www.wrox.com/go/swiftios
If you are an absolute beginner to iOS development, you should progress through the lessons from cover to cover, sequentially. If you have prior experience with iOS development and want to read this book for a particular topic of interest, then you can jump right in with the relevant lessons.
iOS development is a vast topic and no single book can cover everything related to iOS development. However, several lessons contain sources for where to find additional information on the web.
When you're finished reading the book and watching the accompanying videos, you'll find lots of support in the P2P forums.
Learning is often enhanced by seeing in real time what's being taught, which is why most lessons in the book have a corresponding video tutorial available at
. And of course it's vital that you play along at home—fire up Xcode and try out what you read in the book and watch on the videos.www.wrox.com/go/swiftiosvid
To help you get the most from the text and keep track of what's happening, I've used a number of conventions throughout the book.
As for styles in the text:
www.wrox.com
.persistence.properties
.We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration and at the same time you will be helping us provide even higher quality information.
To find the errata page for this book, go to
and locate the title using the Search box or one of the title lists. Then, on the Book Search Results page, click the Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors.www.wrox.com
If you don't spot “your” error on the Errata page, click the Errata Form link and complete the form to send us the error you have found. We'll check the information and, if appropriate, post a message to the book's errata page and fix the problem in subsequent editions of the book.
For author and peer discussion, join the P2P forums at
. The forums are a web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.http://p2p.wrox.com
At
, you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:http://p2p.wrox.com
http://p2p.wrox.com
and click the Register link.Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.
Hello and welcome to the exciting world of iOS application development. iOS is Apple's operating system for mobile devices; the current version at the time of this writing is 8.0. It was originally developed for the iPhone (simply known as iPhone OS back then), and was subsequently extended and renamed in June 2010 to iOS to support the iPad, iPhone, and iPod Touch.
At its core, iOS is Unix-based and has its foundations in MacOS X, which is Apple's desktop operating system. In fact, both iOS and MacOS X share a common code base. As new versions of mobile operating systems have appeared, Apple has brought over more functionality from MacOS X. This is part of Apple's strategy to bridge the difference between desktop and mobile computing.
With the launch of version 8.0, Apple has not only pushed the boundaries on what is achievable on smart phones and tablet computers, but has also given us a brand new programming language called Swift. This book covers iOS development with Swift only, but at the time of this writing, it is possible to create iOS applications with both the older language Objective-C as well as Swift.
This lesson introduces you to the arena of iOS development.
Before you get started on your journey to becoming an iOS developer, you will need some essential resources. This section covers these basic requirements.
To develop apps for the iPhone and the iPad using the official set of tools provided by Apple, you will first need an Intel-based Mac running Mac OS X Yosemite (10.10) with a minimum 4GB of RAM and at least 11GB of free space on your hard disk. You do not need a top-spec model to get started. In fact a Mac Mini or a low-end MacBook will work just fine.
Processor speed is not going to make much difference to you as a developer. You will be better off investing your money in more RAM and hard disk space instead. These are things you can never get enough of. A large screen does help, but it is not essential.
If you are reading this book, chances are that you have used an iPhone, iPad, or iPod Touch and probably even own one or more of these nifty devices.
As far as development is concerned, there aren't many differences between developing for any of these devices. The obvious differences are screen size and the fact that only iPhones can make phone calls. When you are starting out as an iOS developer, you will test your creations on the iOS Simulator. The iOS Simulator is an application that runs on your Mac and simulates several functions of a real iOS device (more on this later).
At some point, however, you will want to test your apps on a physical device. As good as the iOS Simulator may be, you must test on a physical device before submitting your app to the App Store.
Another good reason to test on a physical device is that the processor on your Mac is much faster than that on the iPhone/iPad. Your app may appear to execute much faster on your Mac (in the iOS Simulator) than it does on the real thing.
If the app you are going to make is targeted at iPhone users, you can also use an iPod Touch as the test device. These are significantly cheaper than iPhones and for the most part offer the same functionality as their phone counterparts.
Most of Apple's devices support iOS 8; however, iOS 8 is not supported for the following:
To develop your apps you will need to download the latest version of Xcode and the iOS SDK (Software Development Kit). To do this, you must sign up to the Apple Developer Program to become a registered developer.
The signup process is free and you can immediately begin to develop your first apps. Limitations exist as to what you can do for free. To submit your apps to the App Store, get access to beta versions of the iOS/SDK, or test your apps on a physical device, you need to become a paying member.
Most of the concepts and apps presented in this book will work just fine with the free membership. The only exceptions would be examples that require the camera, accelerometer, and GPS for which you would need to try the app on a physical device.
You can choose from two forms of paid membership as a registered Apple Developer: Individual and Enterprise.
The Individual iOS Developer Program costs $99 a year and is for individuals or companies that want to develop apps that will be distributed through the App Store. You can also test/distribute your apps on up to 100 devices without having to go through the App Store. This form of deployment (without having to submit them to the App Store) is called ad-hoc distribution and is a great way to submit a preview of the app to a client. This form of distribution is covered in detail in Appendix C.
The Enterprise iOS Developer Program costs $299 a year and is for large companies that want to develop apps for internal use and will not distribute these apps through the App Store. With the Enterprise iOS Developer Program there is no restriction to the number of devices on which your in-house application can be installed.
To start the registration process, visit the iOS Dev Center (see Figure 1.1) at
.https://developer.apple.com/programs/enroll/
The Apple iOS SDK (Software Development Kit) is a collection of tools and documentation that you can use to develop iOS apps. The main tools that make up the SDK are:
In addition to these tools, the iOS SDK also includes extensive documentation, sample code, How-To's, and access to the Apple Developer Forums.
The iOS SDK is available as a free download to registered members (registration is free). However, there are benefits to paid membership, including the ability to debug your code on an iOS device, distribution of your applications, and two technical support incidents a year where Apple engineers will provide you code-level assistance.
You can download and install Xcode 7 for Mac OS X El Capitan and the iOS SDK from the Mac App Store (see Figure 1.2).
If you have a paid membership, you can download the latest version of Xcode as well as prior versions by logging in to the iOS developer portal at
.https://developer.apple.com/devcenter/ios/index.action
Whether you intend to develop iOS apps yourself or manage the development of one, you need to be familiar with the basic steps in the development process (see Figure 1.3). This section introduces these steps briefly.
The development of an app begins with a concept. It is good practice to formally put this concept on paper and create a specification. You do not necessarily need to type this specification, although it's a good idea to do so.
At the end of the project you should come back to the specification document to see how the final product that was created compares with the original specification.
As you build your experience developing iOS applications, this difference will become smaller. The specification must address the following points:
A wireframe is a large drawing that contains mockups of each screen of your app as well as lines connecting different screens that indicate the user's journey through your application.
Wireframes are important because they can help identify flaws in your design early on (before any coding has been done). They can also be used to show potential clients how a particular app is likely to look when it's completed.
There is no right or wrong way to make a wireframe. If it is for your personal use, you can just use a few sheets of paper and a pen. If it is for a client, you might want to consider using an illustration package.
The actual process of creating an iOS app involves using the Xcode IDE to type your code. iOS apps can be written in either Swift or Objective-C. This book covers iOS development with Swift only.
An iOS app typically consists of several files of Swift code along with resource files (such as images, audio, and video). These individual files are combined together by a process called compilation into a single file that is installed onto the target device. This single file is usually referred to as the application binary or a build.
It might sound obvious, but you must test your app after it has been developed. As a developer, you test your code frequently as you write it. You must also perform a comprehensive test of the entire application as often as possible to ensure things that were working in the past continue to do so. This form of testing is called regression testing. It helps to make a test plan document. Such a document basically lists all the features that you want to test and the steps required to carry out each test. The document should also clearly list which tests failed. The ones that fail will then need to be fixed and the test plan document can provide the replication procedure for the defect in question.
When your app is ready, you will want to list it in the iTunes App Store. To do so involves submitting your app for review to Apple. Apple has several criteria against which it reviews applications and if your app fails one or more of these criteria it will be rejected—in which case you will need to fix the appropriate code and resubmit. It is best to test your apps thoroughly before submitting them in the first place. Distributing your apps via the App Store is covered in Appendix D.
You must always test on a real iOS device before submitting your app for the App Store review process, or giving it to a client to test. Testing on the iOS Simulator alone is not sufficient.
If you are developing for a client, you will probably need to send the client a testable version of your work periodically for review. The recommended way to do this is by using Apple's TestFlight service, which is covered in Appendix C.
Unless you provide an icon for your application, iOS will use a standard gray icon to represent your application in the home screen (see Figure 1.4).
To replace this icon, you will need to provide one or more PNG files with appropriate dimensions. These dimensions are listed in Table 1.1 and are different for iPhone-based and iPad-based applications.
Table 1.1 Home Screen Icon Sizes
DEVICE | ICON SIZE (IN PIXELS) |
iPhone 4s | 120 x 120 |
iPhone 5 and iPhone 6 | 120 x 120 |
iPhone 6Plus | 180 x 180 |
iPad Retina and iPad Mini Retina | 152 x 152 |
iPad and iPad Mini (without Retina) | 76 x 76 |
You learn to use these icons in this lesson's Try It section.
A launch image is a placeholder image that you must provide as part of your iOS application. When a user taps your application's icon on the home screen, iOS displays this image while the app starts up.
Once your application has finished loading, iOS gives it control and simultaneously hides the launch image. The overall effect of the launch image is to give your users the perception that your application has launched quickly.
Prior to iOS8, as a developer you had to provide a static PNG version of the launch image for every screen size and orientation that was supported by your app.
While it is still possible to provide static launch images, with the launch of iOS 8 Apple has introduced the concept of a single launch file. A launch file is an XIB (or a storyboard file) that describes the user interface for the launch image. An empty document called LaunchScreen.storyboard
is provided with every iOS project that you create.
The idea behind providing a single launch file over several individual launch images is that iOS will generate the launch images it needs from the launch file for the device on which the app is being used.
You learn to use a launch file in this lesson's Try It section.
In this Try It, you build a simple iPhone application using Xcode 7 that displays the text “Hello Swift” in the center of the screen. You will also provide application icons and a launch file.
Download and install the latest version of Xcode and the iOS SDK on your Mac; then launch Xcode.
Main.storyboard
file in Interface Builder (see Figure 1.7).
Main.storyboard
file to select it.Select the label in the storyboard and bring up the Align constraints popup window by clicking the Align button at the bottom right corner of the storyboard (see Figure 1.10).
In this popup window, setup the following options (see Figure 1.11):
Click the Add 2 constraints button in the popup to apply these layout constraints to the label and dismiss the popup.
LaunchScreen.Storyboard
file in the project navigator.Assets.xcassets
item in the project navigator to open the asset bundle. Select the AppIcon asset within this bundle.Use drag-and-drop to assign images to the iPhone App and iPad App placeholders. You can obtain the images from the resources available for this lesson on the book's website at
.www.wrox.com/go/swiftios
iPhoneAppIcon2x.png
.iPhoneAppIcon3x.png
.iPadAppIcon1x.png
.iPadAppIcon2x.png
.After these assignments are made, your scene should resemble Figure 1.12.