Jonathon Manning, Paris Buttield-Addison & Tim Nugent
Total Page:16
File Type:pdf, Size:1020Kb
■ ■ ■ ■ ■ ■ S w i f t ■ ■ Development with Cocoa DEVELOPING FOR THE MAC AND IOS APP STORES Jonathon Manning, Paris Buttield-Addison & Tim Nugent www.itbookshub.com Swift Development with Cocoa 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 tools, this hands-on book shows you how to use the Swift language to make incredible iOS and OS X apps, using Cocoa and Cocoa Touch. Learn how to use Swift in a wide range of real-world situations, with Cocoa features such as EventKit and Core Animation. You’ll pick up Swift language features and syntax along the way, and understand why using Swift (instead of Objective-C) makes iOS and Mac app development easier, faster, and safer. You’ll also work with several exercises to help you practice as you learn. ■ Learn the OS X and iOS application lifecycle ■ Use storyboards to design adaptive interfaces ■ Explore graphics systems, including the built-in 2D and 3D game frameworks ■ Display video and audio with AVFoundation ■ Store data locally with the ilesystem, 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 ■ 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. Paris Buttield-Addison, also a cofounder of Secret Lab, is a mobile software engineer, game designer, and computing researcher. Follow him on Twitter at @parisba. Tim Nugent, not a cofounder of Secret Lab, is a mobile app developer, game designer, PhD student, and author. Follow him on Twitter at @The_McJones. MACINTOSH/IPAD & IPHONE Twitter: @oreillymedia facebook.com/oreilly US $39.99 CAN $41.99 ISBN: 978-1-491-90894-5 www.itbookshub.com Swift Development with Cocoa Jonathon Manning, Paris Buttfield-Addison, and Tim Nugent www.itbookshub.com 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] www.itbookshub.com 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 www.itbookshub.com 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 www.itbookshub.com 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 www.itbookshub.com 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 www.itbookshub.com 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 www.itbookshub.com 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.