📄 Page
1
Jonathon Manning, Paris Buttfield-Addison & Tim Nugent Learning Swift BUILDING APPS FOR macOS, iOS, AND BEYOND 3rd Edition Covers Swift 4+
📄 Page
2
(This page has no text content)
📄 Page
3
Jon Manning, Paris Buttfield-Addison, Tim Nugent Learning Swift Building Apps for macOS, iOS, and Beyond THIRD EDITION Boston Farnham Sebastopol TokyoBeijing
📄 Page
4
978-1-491-98757-5 [LSI] Learning Swift by Jonathon Manning, Paris Buttfield-Addison, and Tim Nugent Copyright © 2018 Secret Lab. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com/safari). For more information, contact our corporate/insti‐ tutional sales department: 800-998-9938 or corporate@oreilly.com. Editor: Rachel Roumeliotis Production Editor: Melanie Yarbrough Copyeditor: Rachel Head Proofreader: Kim Cofer Indexer: Ellen Troutman-Zaig Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest March 2018: Third Edition Revision History for the Third Edition 2018-03-26: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491987575 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning Swift, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
📄 Page
5
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Part I. Welcome to Swift 1. Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Xcode 3 Getting Xcode 4 Creating Your First Project 4 Working with the Xcode Interface 6 The Editor 6 The Toolbar 8 The Navigator 10 Utilities 11 The Debug Area 13 Running Your Code 13 The iOS Simulator 14 Running on a Device 15 Distributing Your Apps 16 The Interface Builder 16 Interfaces in iOS 18 Conclusion 19 2. The Swift Programming Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 The Swift Language 22 Swift 3 Versus 4 24 Playgrounds and Swift 24 Comments 26 iii
📄 Page
6
Imports 27 Variables 27 Operators 30 Collections 31 Arrays 31 Tuples 32 Dictionaries 33 Control Flow 34 Loops 35 Switches 36 Types 39 Working with Strings 39 Sets 42 Enumerations 44 Type Safety and Conversion 46 Optionals 48 Type Casting 51 Functions and Closures 53 Using Functions as Variables 56 Closures 57 Convenience Features 59 The defer Keyword 59 The guard Keyword 60 Making Your Code Swifty 60 Conclusion 61 3. Object-Oriented Development in Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Classes and Objects 63 Initialization and Deinitialization 64 Properties 66 Inheritance 69 Protocols 70 Extensions 72 Access Control 75 Operator Overloading and Custom Operators 78 Subscripts 80 Generics 81 Structures 82 Error Handling 84 Memory Management 87 Design Patterns in Swift 91 Model–View–Controller 92 iv | Table of Contents
📄 Page
7
Delegation 93 Swift Libraries 96 Structuring an App 97 Swift Package Manager 101 Conclusion 107 Part II. Building Selfiegram 4. Setting Up Our App. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Designing Selfiegram 112 Creating the Project 115 The Structure 118 Renaming the Views 120 5. Building the Model Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 The Selfie Object 123 The SelfieStore 127 Testing the SelfieStore 130 Filling Out the Method Stubs 136 6. Building the Selfie List UI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 Creating the Selfie List 145 Improving the Selfie List 151 7. Adding and Deleting Selfies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Deleting Selfies 155 Taking New Selfies 157 8. Viewing and Editing Selfies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 The Selfie Viewer 165 Connecting the Code and the UI 167 Editing a Selfie 172 9. Adding Location Info to the Selfies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Updating the Model 175 Testing Our New Model 178 Showing a Selfie’s Location 179 Expanding the Map 183 Determining Locations 186 Configuring the App to Support Location 186 Talking to the Location Hardware 188 Table of Contents | v
📄 Page
8
10. Building a Settings View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 Building the Settings UI 193 Connecting the Settings into Our Hierarchy 195 Hooking Up the Settings 196 Implementing the Settings 197 11. Reminders and Notifications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 Adding a Reminder to the Settings 201 Creating a Notification 203 Part III. Polishing Selfiegram 12. Theming and Sharing Selfiegram. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 Custom Fonts 214 Making the Theme 217 Sharing Selfies 221 Sharing from the Detail View Controller 222 Sharing from the List View Controller 224 13. Custom Views and View Controllers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 A Camera View 228 The Camera View Controller 231 Building the UI 231 Connecting the UI 234 Talking to the Camera 234 Calling the Capture View Controller 240 14. Image Overlays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 Creating the Overlay Model 245 Testing the Overlay Manager 252 Writing the Tests 252 Returning Available Overlays 255 Downloading Overlay Information 256 Downloading Overlay Images 258 15. Overlay UI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 Building the UI 263 Hooking Up the UI 266 Creating the Overlay View 266 Presenting the Overlays 268 Initial Setup 268 vi | Table of Contents
📄 Page
9
Drawing Eyebrows 271 Vision and Image Detection 274 Connecting It into the App 279 16. Localization and Internationalization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Internationalization 284 Generating the String Table 286 Localization 287 Translating the Strings 290 Testing Locales 290 Pseudolanguages 292 Previewing Localizations 294 Conclusion 296 Part IV. Beyond Developing Selfiegram 17. Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 The Debugger 299 Breakpoints 300 Inspecting Code 304 Controlling Program Flow 307 Performance 309 Instruments 310 18. UI Tests. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 UI Testing Classes 313 Writing UI Tests 314 A Basic Test 314 Recording UI Actions 315 Checking if Elements Exist 318 Handling UI Interruptions 319 19. Automating Chores with Fastlane. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 The Fastlane Tools 322 Installing Fastlane 323 Installing via Homebrew 324 Installing via RubyGems 324 Installing via Direct Download 324 Setting Up a Project 324 Doing a Build 325 Configuring a Fastfile 327 Table of Contents | vii
📄 Page
10
20. Using Fastlane’s Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 Code Signing with match 329 The Problem That Match Solves 329 match’s Solution 332 Generating Screenshots Using snapshot 333 Using Boarding to Add Testers to TestFlight 337 Managing Your App’s Presence on the App Store Using deliver 339 Getting the Metadata 340 Submitting New Metadata 340 Looking Further 341 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 viii | Table of Contents
📄 Page
11
Preface Welcome to Learning Swift! This book will help you put the Swift programming lan‐ guage into practice by walking you through the development of a complete applica‐ tion for iOS that features a wide array of features, including camera access, working with the filesystem, face detection, and the iOS graphics system. Along the way, we’ll also introduce you to new and advanced topics in the Swift programming language. Swift is a pretty amazing modern language, taking the best from other newer lan‐ guages without reinventing the wheel. Swift is easy to write, easy to read, and hard to make big mistakes in. Our philosophy is that the best way to learn Swift is to build apps using it! To build apps, though, you need a great framework, and Apple has one of the best ones for building high-quality, featureful software: Cocoa Touch. This book could quite easily be titled Learning Cocoa Touch with Swift, or something similar, because the frame‐ works are just as important as the language itself. At the time of writing, Swift is cur‐ rently at version 4, and has a bright future ahead of it. Resources Used in This Book We recommend following along with the book by writing code yourself as you pro‐ gress through each chapter. If you get stuck, or just want to archive a copy of the code, you can find what you need via our website. Audience and Approach This book is solely focused on Swift 4 and does not cover the use of Objective-C. We might mention it occasionally, but we don’t expect you to know how to use it. We first cover the basics of the Swift 4 language, and then move on to teach as much of the language as we can, as well as the use of Cocoa Touch, through the construction of Selfiegram, a photo-taking app for iOS. ix
📄 Page
12
This book’s approach differs from that of other programming books that you may have encountered. As we’ve mentioned, we believe that the best way to learn Swift is to build something using it. We assume that you’re a reasonably capable programmer, but we don’t assume you’ve ever developed for iOS or used Swift or Objective-C before. We also assume that you’re fairly comfortable navigating macOS and iOS as a user. Organization of This Book In this book, we’ll be talking about Cocoa Touch, the framework used for developing iOS applications. Along the way, we’ll also be covering Swift, including its syntax and features. In Part I, Welcome to Swift, we begin with a look at the tools used for programming with Swift, as well as the Apple Developer Program. Then we move on to the basics of the Swift programming language and structuring a program for Apple’s platforms, as well as common design patterns. In Part II, Building Selfiegram, we start building Selfiegram, the iOS photo-taking application that’s the focus of the book. In this part, we’ll build the foundational fea‐ tures, like the ability to take photos and store them on disk. In Part III, Polishing Selfiegram, we add a number of particularly interesting features, including a custom camera view, face detection, network access, and theming the app. In Part IV, Beyond Developing Selfiegram, we discuss a number of features and tools that can help you in your further development work, including Xcode’s debugging and profiling tools, as well as third-party tools that can make your life easier. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Also used for commands and command- line output. x | Preface
📄 Page
13
This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, errata, etc.) is available for down‐ load at our website. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a signifi‐ cant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Learning Swift, 3rd Edition, by Jona‐ thon Manning, Paris Buttfield-Addison, and Tim Nugent (O’Reilly). Copyright 2018 Secret Lab, 978-1-491-98757-5.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. Preface | xi
📄 Page
14
O’Reilly Safari Safari (formerly Safari Books Online) is a membership-based training and reference platform for enterprise, government, educators, and individuals. Members have access to thousands of books, training videos, Learning Paths, interac‐ tive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐ sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and Course Technology, among others. For more information, please visit http://oreilly.com/safari. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/learning-swift-3e. To comment or ask technical questions about this book, send email to bookques‐ tions@oreilly.com. For more information about our books, courses, conferences, and news, see our web‐ site at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia xii | Preface
📄 Page
15
Acknowledgments Jon thanks his mother, father, and the rest of his crazily extended family for their tre‐ mendous support. Paris thanks his mother, without whom he wouldn’t be doing anything nearly as interesting, let alone writing books. Tim thanks his parents and family for putting up with his rather lackluster approach to life. We’d all like to thank Rachel Roumeliotis, whose skill and advice were invaluable to completing the book. Likewise, all the O’Reilly Media staff we’ve interacted with over the course of writing the book have been the absolute gurus of their fields. A huge thank you to Tony Gray and the Apple University Consortium (AUC) for the monumental boost they gave us and others listed on this page. We wouldn’t be writ‐ ing this book if it weren’t for them. And now you’re writing books, too, Tony—sorry about that! Thanks also to Neal Goldstein, who deserves full credit and/or blame for getting us into the whole book-writing racket. We’re thankful for the support of the goons at MacLab (who know who they are and continue to stand watch for Admiral Dolphin’s inevitable apotheosis), as well as pro‐ fessor Christopher Lueg, Dr. Leonie Ellis, and the rest of the staff at the University of Tasmania for putting up with us. “Apologies” to Mark Pesce. He knows why. Additional thanks to Mars G., Dave J., Rex S., Nic W., Andrew B., Jess L., and every‐ one else who inspires us and helps us. And very special thanks to Steve Jobs, without whom this book (and many others like it) would not have reason to exist. Thanks also to our tech reviewers, with special thanks to Chris Devers and Nik Saers for their thoroughness and professionalism. Finally, thank you very much for buying our book—we appreciate it! And if you have any feedback, please let us know. You can email us at lab@secretlab.com.au and find us on Twitter at @thesecretlab. Preface | xiii
📄 Page
16
(This page has no text content)
📄 Page
17
PART I Welcome to Swift
📄 Page
18
(This page has no text content)
📄 Page
19
CHAPTER 1 Getting Started Welcome to Learning Swift! In this book, we’ll take you from knowing nothing about the Swift programming language to building a full-featured app for iOS 11. Along the way, we’ll explore the libraries, frameworks, and features available to you as a devel‐ oper of software for iPhones and iPads. We’ll be covering practical solutions to com‐ mon problems, as well as the details of the Swift language itself. We’ll begin with some important setup work that needs to be done before you can start using the developer tools. In particular, we’ll take a look at the Apple Developer Program, and how to get your account set up so that you can build your app on a device. This book assumes that you’ve got access to two things: a Mac and an iOS device of some kind (that is, an iPhone or iPad). The Mac is mandatory; without it, you can’t run Xcode, which is the tool for writing your code, designing your interfaces, and build‐ ing and running your code. Your Mac will need to be capable of running Xcode 9.2 or newer, which means that it needs to run macOS 10.12 or higher. The iOS device is not absolutely mandatory, but you won’t be able to follow all of the book without it, because the app that we’re mak‐ ing in this book makes use of hardware features that aren’t present in the iOS simulator. The device you use needs to be able to run iOS 11 or later. Xcode Xcode is the development environment used for all development work done on Apple platforms. As you work through this book, you’ll be spending most of your time 3
📄 Page
20
inside Xcode. With that in mind, we’ll be spending the rest of this chapter getting a copy of Xcode, setting it up, and getting familiar with the interface. Getting Xcode Xcode is available via the App Store. To get a copy, search the App Store for Xcode or go to Apple’s developer downloads page, find Xcode, and click the Download button. If you prefer not to use the App Store, you can download it directly via Apple’s Downloads for Apple Developers page. This page lists all versions of Xcode, so be sure to get the most recent one. Once it’s installed, go ahead and launch it. You’ll be greeted by the welcome screen seen in Figure 1-1. Figure 1-1. The Welcome to Xcode screen Creating Your First Project Since we want to take a tour of Xcode, we’ll start by creating an empty project (we’ll repeat this step in Chapter 4, when we start building this book’s main app): 1. Click “Create a new Xcode project.” The template chooser (seen in Figure 1-2) will appear. 4 | Chapter 1: Getting Started