Swift Development with Cocoa wS Ready to build apps for iPhone, iPad, and Mac now that Swift has landed? If you’re an experienced programmer who’s never touched Apple developer w i tools, this hands-on book shows you how to use the Swift language to t make incredible iOS and OS X apps, using Cocoa and Cocoa Touch. hi f Learn how to use Swift in a wide range of real-world situations, with t C Cocoa features such as EventKit and Core Animation. You’ll pick up Swift D language features and syntax along the way, and understand why using o Swift (instead of Objective-C) makes iOS and Mac app development easier, e c faster, and safer. You’ll also work with several exercises to help you practice v o as you learn. e a l ■ Learn the OS X and iOS application lifecycle o ■ Use storyboards to design adaptive interfaces p ■ Explore graphics systems, including the built-in 2D and 3D m game frameworks e ■ Display video and audio with AVFoundation n S wift ■ Store data locally with the filesystem, or on the network with t iCloud ■ Display lists or collections of data with table views and collection views ■ Build apps that let users create, edit, and work with documents Development ■ Use MapKit, Core Location, and Core Motion to interact with the world Jonathan Manning, cofounder of Secret Lab, is a mobile software engineer, game designer, and computing researcher. Follow him on Twitter at @desplesda. B with Cocoa u Paris Buttfield-Addison, also a cofounder of Secret Lab, is a mobile software engineer, t t game designer, and computing researcher. Follow him on Twitter at @parisba. fi e l Tim Nugent, not a cofounder of Secret Lab, is a mobile app developer, game d &-M designer, PhD student, and author. Follow him on Twitter at @The_McJones. NAa d ugedisnnin nog DEVELOPING FOR THE MAC AND IOS APP STORES MACINTOSH/IPAD &IPHONE Twitter: @oreillymedia tn, facebook.com/oreilly US $39.99 CAN $41.99 ISBN: 978-1-491-90894-5 Jonathon Manning, Paris Buttfield-Addison & Tim Nugent Swift Development with Cocoa wS Ready to build apps for iPhone, iPad, and Mac now that Swift has landed? If w you’re an experienced programmer who’s never touched Apple developer i tools, this hands-on book shows you how to use the Swift language to t make incredible iOS and OS X apps, using Cocoa and Cocoa Touch. hi f t Learn how to use Swift in a wide range of real-world situations, with C Cocoa features such as EventKit and Core Animation. You’ll pick up Swift D o language features and syntax along the way, and understand why using e Swift (instead of Objective-C) makes iOS and Mac app development easier, c v faster, and safer. You’ll also work with several exercises to help you practice o e as you learn. a l o ■ Learn the OS X and iOS application lifecycle p ■ Use storyboards to design adaptive interfaces m ■ Explore graphics systems, including the built-in 2D and 3D game frameworks e n ■ Display video and audio with AVFoundation t S wift ■ Store data locally with the filesystem, or on the network with iCloud ■ Display lists or collections of data with table views and collection views ■ Build apps that let users create, edit, and work with documents Development ■ Use MapKit, Core Location, and Core Motion to interact with the world Jonathon Manning, cofounder of Secret Lab, is a mobile software engineer, game designer, and computing researcher. Follow him on Twitter at @desplesda. B with Cocoa u Paris Buttfield-Addison, also a cofounder of Secret Lab, is a mobile software engineer, t t game designer, and computing researcher. Follow him on Twitter at @parisba. fi e l Tim Nugent, not a cofounder of Secret Lab, is a mobile app developer, game d &-M designer, PhD student, and author. Follow him on Twitter at @The_McJones. NAa d ugedisnnin nog DEVELOPING FOR THE MAC AND IOS APP STORES MACINTOSH/IPAD & IPHONE Twitter: @oreillymedia tn, facebook.com/oreilly US $39.99 CAN $41.99 ISBN: 978-1-491-90894-5 Jonathon Manning, Paris Buttfield-Addison & Tim Nugent Swift Development with Cocoa Jonathon Manning, Paris Buttfield-Addison, and Tim Nugent Swift Development with Cocoa by Jonathon Manning, Paris Buttfield-Addison, and Tim Nugent Copyright © 2015 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://safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected]. Editor: Rachel Roumeliotis Indexer: Wendy Catalano Production Editor: Matthew Hacker Cover Designer: Ellie Volckhausen Copyeditor: Jasmine Kwityn Interior Designer: David Futato Proofreader: Charles Roumeliotis Illustrator: Rebecca Demarest December 2014: First Edition Revision History for the First Edition: 2014-12-08: First release See http://oreilly.com/catalog/errata.csp?isbn=9781491908945 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Swift Development with Cocoa, the cover image of an Australasian gannet, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While the publisher and the authors have used good faith efforts to ensure that the information and in‐ structions 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. ISBN: 978-1-491-90894-5 [M] Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1. Cocoa Development Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 The Mac and iOS Developer Programs 1 Registering for a Developer Program 2 Downloading Xcode 3 Creating Your First Project with Xcode 4 The Xcode Interface 7 Developing a Simple Swift Application 13 Designing the Interface 13 Connecting the Code 15 Using the iOS Simulator 17 Testing iOS Apps with TestFlight 19 2. Programming with Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 The Swift Programming Language 21 Playgrounds 23 Variables and Constants 24 Types 26 Tuples 28 Arrays 28 Dictionaries 29 Control Flow 30 Switches 33 Functions and Closures 35 Using Functions as Variables 37 Closures 39 Objects 40 Inheritance 42 iii Initialization and Deinitialization 42 Properties 44 Protocols 46 Extensions 47 Access Control 49 Operators 50 Generics 51 Interoperating with Objective-C 52 Using Objective-C and Swift in the Same Project 52 Using Swift Objects in Objective-C 53 Using Objective-C Objects in Swift 53 Modules 54 Memory Management 54 Working with Strings 55 Comparing Strings 56 Searching Strings 57 Data 57 Loading Data from Files and URLs 57 Serialization and Deserialization 58 Design Patterns in Cocoa 59 Model-View-Controller 59 Delegation 60 3. Applications on OS X and iOS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 What Is an Application? 63 Applications, Frameworks, Utilities, and More 64 What Are Apps Composed Of? 65 Using NSBundle to Find Resources in Applications 67 The Application Life Cycle 68 OS X Applications 68 iOS Applications 70 The Application Sandbox 75 Application Restrictions 76 Notifications with NSNotification 78 4. Graphical User Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Interfaces in OS X and iOS 81 MVC and Application Design 82 Nib Files and Storyboards 82 Structure of a Nib File 83 Storyboards 86 Outlets and Actions 87 iv | Table of Contents How Nib Files and Storyboards Are Loaded 88 Constructing an Interface 89 Guidelines and Constraints 90 Building an App with Nibs and Constraints 91 Interfaces on iOS 95 Launch Screen Files 97 UI Dynamics 98 UI and Gravity 98 Snapping UI 99 Core Animation 100 Layers 101 Animations 102 5. Closures and Operation Queues. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Closures in Cocoa 106 Concurrency with Operation Queues 107 Operation Queues and NSOperation 108 Performing Work on Operation Queues 108 Putting It All Together 109 6. Drawing Graphics in Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 How Drawing Works 115 The Pixel Grid 117 Retina Displays 118 Pixels and Screen Points 119 Drawing in Views 120 Frame Rectangles 120 Bounds Rectangles 121 Building a Custom View 122 Filling with a Solid Color 123 Working with Paths 124 Creating Custom Paths 126 Multiple Subpaths 128 Shadows 129 Gradients 132 Transforms 135 7. SpriteKit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 SpriteKit’s Architecture 139 Making an App That Uses SpriteKit 140 Working with SpriteKit Scenes 141 SpriteKit Nodes 143 Table of Contents | v Putting Sprites in Scenes 145 Responding to Touches 146 Working with Textures 147 Texture Atlases 148 Working with Text 149 Animating Content with Actions 150 Using Shape Nodes 151 Using Image Effect Nodes 153 Adding Physics to SpriteKit Objects 154 Adding Joints to SpriteKit Objects 155 Lighting SpriteKit Scenes 156 Constraints 157 Using Shaders in SpriteKit 157 Using SpriteKit Editor 160 8. SceneKit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 SceneKit Structure 164 Working with SceneKit 165 Adding a SceneKit View 165 Adding a Scene 166 Adding a Camera 167 Adding a 3D Object 168 Adding Lights 169 Animating Content in the Scene 170 Creating Text Geometry 172 Combining Animations 173 Working with Materials 174 Normal Mapping 176 Hit Testing 178 Constraints 181 Loading Data from COLLADA Files 182 Adding Physics to the Scene 185 9. Audio and Video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 AV Foundation 189 Playing Video with AVPlayer 190 AVPlayerLayer 191 Putting It Together 191 AVKit 195 AVKit on iOS 197 Playing Sound with AVAudioPlayer 199 Speech Synthesis 200 vi | Table of Contents Working with the Photo Library 201 Capturing Photos and Video from the Camera 202 Building a Photo Application 204 The Photo Library 207 10. iCloud and Data Storage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 Preferences 209 Registering Default Preferences 210 Accessing Preferences 211 Setting Preferences 211 Working with the Filesystem 212 Using NSFileManager 213 File Storage Locations 217 Working with the Sandbox 217 Enabling Sandboxing 217 Open and Save Panels 218 Security-Scoped Bookmarks 219 iCloud 220 What iCloud Stores 221 Setting Up for iCloud 222 Testing Whether iCloud Works 222 Storing Settings 223 Handling External Changes 224 The iOS Counterpart 225 iCloud Storage 228 iCloud Storage on OS X 228 iCloud Storage on iOS 233 Document Pickers 235 Using iCloud Well 239 11. Cocoa Bindings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 Binding Views to Models 241 A Simple Bindings App 242 Binding to Controllers 245 Array and Object Controllers 246 A More Complex Bindings App 247 12. Table Views and Collection Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 Data Sources and Delegates 255 Table Views 256 UITableView on iOS 256 NSTableView on OS X 264 Table of Contents | vii Collection Views 270 UICollectionView on iOS 270 13. Document-Based Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 The NSDocument and UIDocument Classes 276 Document Objects in MVC 276 Kinds of Documents 277 The Role of Documents 278 Document-Based Applications on OS X 278 Autosaving and Versions 279 Representing Documents with NSDocument 279 Saving Simple Data 280 Saving More Complex Data 282 Document-Based Applications on iOS 286 14. Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Connections 293 NSURL 294 NSURLRequest 295 NSURLSession 296 NSURLResponse and NSHTTPURLResponse 296 Building a Networked Application 297 Bonjour Service Discovery 299 Browsing for Shared iTunes Libraries 299 Multipeer Connectivity 301 15. Working with the Real World. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 Working with Location 307 Location Hardware 308 The Core Location Framework 310 Working with Core Location 311 Geocoding 314 Region Monitoring and iBeacons 317 Locations and Privacy 320 Maps 320 Using Maps 320 Annotating Maps 321 Maps and Overlays 322 Device Motion 324 Working with Core Motion 325 Using the Built-in Altimeter 329 Using the Pedometer 330 viii | Table of Contents