100% found this document useful (1 vote)
16 views

Beginning iPhone Development With Swift 2 Exploring the iOS SDK 2nd Edition David Mark instant download

The document provides information about the book 'Beginning iPhone Development with Swift 2', which teaches readers how to build iPhone and iPad apps using the iOS SDK and Swift 2. It includes links to various related eBooks and details about the book's content, authors, and copyright information. The book is dedicated to the memory of Steve Jobs and includes a comprehensive table of contents outlining the chapters and topics covered.

Uploaded by

matewadhey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
16 views

Beginning iPhone Development With Swift 2 Exploring the iOS SDK 2nd Edition David Mark instant download

The document provides information about the book 'Beginning iPhone Development with Swift 2', which teaches readers how to build iPhone and iPad apps using the iOS SDK and Swift 2. It includes links to various related eBooks and details about the book's content, authors, and copyright information. The book is dedicated to the memory of Steve Jobs and includes a comprehensive table of contents outlining the chapters and topics covered.

Uploaded by

matewadhey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Beginning iPhone Development With Swift 2

Exploring the iOS SDK 2nd Edition David Mark pdf


download

https://ebookgate.com/product/beginning-iphone-development-with-
swift-2-exploring-the-ios-sdk-2nd-edition-david-mark/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Beginning iPhone Development Exploring the iPhone SDK 1st


Edition Jeff Lamarche

https://ebookgate.com/product/beginning-iphone-development-exploring-
the-iphone-sdk-1st-edition-jeff-lamarche/

ebookgate.com

iOS 9 SDK Development Creating iPhone and iPad Apps with


Swift 1st Edition Adamson

https://ebookgate.com/product/ios-9-sdk-development-creating-iphone-
and-ipad-apps-with-swift-1st-edition-adamson/

ebookgate.com

The iPhone Developer s Cookbook Building Applications with


the iPhone 3 0 SDK 2nd Edition Erica Sadun

https://ebookgate.com/product/the-iphone-developer-s-cookbook-
building-applications-with-the-iphone-3-0-sdk-2nd-edition-erica-sadun/

ebookgate.com

iOS Swift Game Development Cookbook 2nd Edition Simple


Solutions for Game Development Problems Jonathon Manning

https://ebookgate.com/product/ios-swift-game-development-cookbook-2nd-
edition-simple-solutions-for-game-development-problems-jonathon-
manning/
ebookgate.com
iOS 12 App Development Essentials Learn to Develop iOS 12
Apps with Xcode 10 and Swift 4 Neil Smyth

https://ebookgate.com/product/ios-12-app-development-essentials-learn-
to-develop-ios-12-apps-with-xcode-10-and-swift-4-neil-smyth/

ebookgate.com

Beginning IOS Storyboarding with Xcode Lewis

https://ebookgate.com/product/beginning-ios-storyboarding-with-xcode-
lewis/

ebookgate.com

Beginning Java 2 SDK 1 4 edition Ivor Horton

https://ebookgate.com/product/beginning-java-2-sdk-1-4-edition-ivor-
horton/

ebookgate.com

Head First iPhone Development covers iPhone 3 1 SDK a


brain friendly guide 1st ed Edition Pilone

https://ebookgate.com/product/head-first-iphone-development-covers-
iphone-3-1-sdk-a-brain-friendly-guide-1st-ed-edition-pilone/

ebookgate.com

IPhone SDK 3 Programming Advanced Mobile Development for


Apple IPhone and IPod Touch 1st Edition Maher Ali

https://ebookgate.com/product/iphone-sdk-3-programming-advanced-
mobile-development-for-apple-iphone-and-ipod-touch-1st-edition-maher-
ali/
ebookgate.com
Beginning
iPhone Development
with Swift 2
Exploring the iOS SDK

Learn to build iPhone and iPad apps
using the iOS SDK and Swift 2

David Mark
Kim Topley
Jack Nutting
Fredrik Olsson
Jeff LaMarche

www.allitebooks.com
Beginning iPhone
Development with
Swift 2
Exploring the iOS SDK

David Mark
Kim Topley
Jack Nutting
Frederik Olsson
Jeff LaMarche

www.allitebooks.com
Beginning iPhone Development with Swift: Exploring the iOS SDK
Copyright © 2015 by David Mark, Kim Topley, Jack Nutting, Frederik Olsson, and Jeff LaMarche
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with
reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed
on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or
parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its
current version, and permission for use must always be obtained from Springer. Permissions for use may be
obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under
the respective Copyright Law.
ISBN-13 (pbk): 978-1-4842-1753-5
ISBN-13 (electronic): 978-1-4842-1754-2
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol
with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only
in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director: Welmoed Spahr
Lead Editor: Steve Anglin
Development Editor: Matthew Moodie
Technical Reviewer: Bruce Wade
Editorial Board: Steve Anglin, Pramila Balan, Louise Corrigan, Jonathan Gennick, Robert Hutchinson,
Celestin Suresh John, Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie,
Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing
Coordinating Editor: Mark Powers
Copy Editor: Kimberly Burton
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com,
or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer
Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our Special
Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this text is available to
readers at www.apress.com/9781484217535. For detailed information about how to locate your book’s source
code, go to www.apress.com/source-code/. Readers can also access source code at SpringerLink in the
Supplementary Material section for each chapter.

www.allitebooks.com
This book is dedicated to the memory of Steve Jobs. We continue to be inspired by
his spirit and his vision.
—David Mark and Jack Nutting

Dedicated to my mom and dad, who bought my first computer.


—Fredrik Olsson

For Diana.
—Kim Topley

www.allitebooks.com
Contents at a Glance
About the Authors���������������������������������������������������������������������������������������������������xxi
About the Technical Reviewer������������������������������������������������������������������������������xxiii


■Chapter 1: Welcome to the Swift Jungle��������������������������������������������������������������� 1

■Chapter 2: Appeasing the Tiki Gods��������������������������������������������������������������������� 13

■Chapter 3: Handling Basic Interaction����������������������������������������������������������������� 55

■Chapter 4: More User Interface Fun�������������������������������������������������������������������� 91

■Chapter 5: Rotation and Adaptive Layout���������������������������������������������������������� 141

■Chapter 6: Multiview Applications�������������������������������������������������������������������� 181

■Chapter 7: Tab Bars and Pickers ���������������������������������������������������������������������� 211

■Chapter 8: Introduction to Table Views������������������������������������������������������������� 255

■Chapter 9: Navigation Controllers and Table Views������������������������������������������� 307

■Chapter 10: Collection View and Stack View����������������������������������������������������� 341

■Chapter 11: Using Split Views and Popovers����������������������������������������������������� 371

■Chapter 12: Application Settings and User Defaults������������������������������������������ 411

■Chapter 13: Basic Data Persistence������������������������������������������������������������������ 453

■Chapter 14: Documents and iCloud������������������������������������������������������������������� 503

www.allitebooks.com
vi Contents at a Glance


■Chapter 15: Grand Central Dispatch, Background Processing, and You������������ 539

■Chapter 16: Drawing with Core Graphics���������������������������������������������������������� 575

■Chapter 17: Getting Started with SpriteKit�������������������������������������������������������� 603

■Chapter 18: Taps, Touches, and Gestures���������������������������������������������������������� 655

■Chapter 19: Where Am I? Finding Your Way with Core Location and Map Kit���� 689

■Chapter 20: Whee! Gyro and Accelerometer!���������������������������������������������������� 711

■Chapter 21: The Camera and Photo Library������������������������������������������������������� 737

■Chapter 22: Application Localization����������������������������������������������������������������� 749

■Appendix A: A Swift Introduction to Swift��������������������������������������������������������� 777

Index��������������������������������������������������������������������������������������������������������������������� 839

www.allitebooks.com
Contents
About the Authors���������������������������������������������������������������������������������������������������xxi
About the Technical Reviewer������������������������������������������������������������������������������xxiii


■Chapter 1: Welcome to the Swift Jungle��������������������������������������������������������������� 1
What This Book Is������������������������������������������������������������������������������������������������������������� 1
What You Need����������������������������������������������������������������������������������������������������������������� 2
Developer Options���������������������������������������������������������������������������������������������������������������������������������� 3
What You Need to Know������������������������������������������������������������������������������������������������������������������������� 4

What’s Different About Coding for iOS?���������������������������������������������������������������������������� 5


Only One Active Application�������������������������������������������������������������������������������������������������������������������� 5
Only One Window������������������������������������������������������������������������������������������������������������������������������������ 5
Limited Access��������������������������������������������������������������������������������������������������������������������������������������� 6
Limited Response Time�������������������������������������������������������������������������������������������������������������������������� 6
Limited Screen Size�������������������������������������������������������������������������������������������������������������������������������� 6
Limited System Resources��������������������������������������������������������������������������������������������������������������������� 8
Some New Stuff�������������������������������������������������������������������������������������������������������������������������������������� 8
A Different Approach������������������������������������������������������������������������������������������������������������������������������ 8

vii

www.allitebooks.com
viii Contents

What’s in This Book���������������������������������������������������������������������������������������������������������� 9


What’s New in This Update?������������������������������������������������������������������������������������������� 11
Swift and Xcode Versions����������������������������������������������������������������������������������������������� 11
Are You Ready?�������������������������������������������������������������������������������������������������������������� 12

■Chapter 2: Appeasing the Tiki Gods��������������������������������������������������������������������� 13
Setting Up Your Project in Xcode������������������������������������������������������������������������������������ 13
The Xcode Project Window������������������������������������������������������������������������������������������������������������������� 18
A Closer Look at Our Project����������������������������������������������������������������������������������������������������������������� 28

Introducing Xcode’s Interface Builder���������������������������������������������������������������������������� 29


File Formats������������������������������������������������������������������������������������������������������������������������������������������ 30
The Storyboard������������������������������������������������������������������������������������������������������������������������������������� 31
The Utilities Area����������������������������������������������������������������������������������������������������������������������������������� 33
Adding a Label to the View������������������������������������������������������������������������������������������������������������������� 35
Changing Attributes������������������������������������������������������������������������������������������������������������������������������ 39

Some iPhone Polish: Finishing Touches������������������������������������������������������������������������� 41


The Launch Screen��������������������������������������������������������������������������������������������������������� 45
Running the Application on a Device������������������������������������������������������������������������������ 48
Bring It on Home������������������������������������������������������������������������������������������������������������ 53

■Chapter 3: Handling Basic Interaction����������������������������������������������������������������� 55
The Model-View-Controller Paradigm���������������������������������������������������������������������������� 56
Creating Our Project������������������������������������������������������������������������������������������������������� 57
Looking at the View Controller��������������������������������������������������������������������������������������� 58
Understanding Outlets and Actions������������������������������������������������������������������������������������������������������ 60
Cleaning Up the View Controller����������������������������������������������������������������������������������������������������������� 62
Designing the User Interface���������������������������������������������������������������������������������������������������������������� 63
Trying It Out������������������������������������������������������������������������������������������������������������������������������������������ 73
Previewing Layout�������������������������������������������������������������������������������������������������������������������������������� 82
Adding Some style�������������������������������������������������������������������������������������������������������������������������������� 85

Looking at the Application Delegate������������������������������������������������������������������������������� 86


Bring It on Home������������������������������������������������������������������������������������������������������������ 89

www.allitebooks.com
Contents ix


■Chapter 4: More User Interface Fun�������������������������������������������������������������������� 91
A Screen Full of Controls������������������������������������������������������������������������������������������������ 91
Active, Static, and Passive Controls�������������������������������������������������������������������������������� 95
Creating the Application������������������������������������������������������������������������������������������������� 97
Implementing the Image View and Text Fields��������������������������������������������������������������� 97
Adding the Image View������������������������������������������������������������������������������������������������������������������������� 98
Resizing the Image View�������������������������������������������������������������������������������������������������������������������� 100
Setting View Attributes����������������������������������������������������������������������������������������������������������������������� 102
Adding the Text Fields������������������������������������������������������������������������������������������������������������������������� 105
Adding Constraints����������������������������������������������������������������������������������������������������������������������������� 113
Creating and Connecting Outlets�������������������������������������������������������������������������������������������������������� 115

Closing the Keyboard��������������������������������������������������������������������������������������������������� 116


Closing the Keyboard When Done Is Tapped�������������������������������������������������������������������������������������� 117
Touching the Background to Close the Keyboard������������������������������������������������������������������������������� 118
Adding the Slider and Label��������������������������������������������������������������������������������������������������������������� 121
Creating and Connecting the Actions and Outlets������������������������������������������������������������������������������ 123
Implementing the Action Method�������������������������������������������������������������������������������������������������������� 123

Implementing the Switches, Button, and Segmented Control�������������������������������������� 124


Implementing the Switch Actions������������������������������������������������������������������������������������������������������� 128

Spiffing Up the Button�������������������������������������������������������������������������������������������������� 131


Stretchable Images����������������������������������������������������������������������������������������������������������������������������� 131
Control States������������������������������������������������������������������������������������������������������������������������������������� 132
Connecting and Creating the Button Outlets and Actions������������������������������������������������������������������� 133

Implementing the Segmented Control Action��������������������������������������������������������������� 133


Implementing the Action Sheet and Alert��������������������������������������������������������������������� 134
Showing an Action Sheet�������������������������������������������������������������������������������������������������������������������� 135
Showing an Alert�������������������������������������������������������������������������������������������������������������������������������� 139
Crossing the Finish Line����������������������������������������������������������������������������������������������� 140

www.allitebooks.com
x Contents


■Chapter 5: Rotation and Adaptive Layout���������������������������������������������������������� 141
The Mechanics of Rotation������������������������������������������������������������������������������������������� 142
Points, Pixels, and the Retina Display������������������������������������������������������������������������������������������������� 143
Handling Rotation������������������������������������������������������������������������������������������������������������������������������� 143

Choosing Your View Orientations���������������������������������������������������������������������������������� 144


Supported Orientations at the App Level�������������������������������������������������������������������������������������������� 144
Per-Controller Rotation Support���������������������������������������������������������������������������������������������������������� 146

Designing an Interface Using Constraints�������������������������������������������������������������������� 148


Overriding Default Constraints����������������������������������������������������������������������������������������������������������� 152
Full-Width Labels�������������������������������������������������������������������������������������������������������������������������������� 154

Creating Adaptive Layouts�������������������������������������������������������������������������������������������� 157


The Restructure Application��������������������������������������������������������������������������������������������������������������� 158
Size Classes���������������������������������������������������������������������������������������������������������������������������������������� 162
Size Classes and Storyboards������������������������������������������������������������������������������������������������������������ 165
Creating the iPhone Landscape Layout���������������������������������������������������������������������������������������������� 168
Adding the iPad Layout����������������������������������������������������������������������������������������������������������������������� 175

Rotating Out of Here����������������������������������������������������������������������������������������������������� 179



■Chapter 6: Multiview Applications�������������������������������������������������������������������� 181
Common Types of Multiview Apps�������������������������������������������������������������������������������� 181
The Architecture of a Multiview Application����������������������������������������������������������������� 187
The Root Controller����������������������������������������������������������������������������������������������������������������������������� 189
Anatomy of a Content View����������������������������������������������������������������������������������������������������������������� 190

Building View Switcher������������������������������������������������������������������������������������������������ 190


Renaming the View Controller������������������������������������������������������������������������������������������������������������ 191
Adding the Content View Controllers�������������������������������������������������������������������������������������������������� 193
Modifying SwitchingViewController.swift������������������������������������������������������������������������������������������� 193
Building a View with a Toolbar������������������������������������������������������������������������������������������������������������ 194
Linking the Toolbar Button to the View Controller������������������������������������������������������������������������������ 197
Writing the Root View Controller��������������������������������������������������������������������������������������������������������� 198
Implementing the Content Views�������������������������������������������������������������������������������������������������������� 203
Animating the Transition��������������������������������������������������������������������������������������������������������������������� 206

Switching Off���������������������������������������������������������������������������������������������������������������� 209

www.allitebooks.com
Contents xi


■Chapter 7: Tab Bars and Pickers ���������������������������������������������������������������������� 211
The Pickers Application������������������������������������������������������������������������������������������������ 212
Delegates and Data Sources���������������������������������������������������������������������������������������� 217
Creating the Pickers Application���������������������������������������������������������������������������������� 218
Creating the View Controllers������������������������������������������������������������������������������������������������������������� 218
Creating the Tab Bar Controller����������������������������������������������������������������������������������������������������������� 219
The Initial Test Run����������������������������������������������������������������������������������������������������������������������������� 223

Implementing the Date Picker�������������������������������������������������������������������������������������� 224


Implementing the Single-Component Picker���������������������������������������������������������������� 228
Building the View�������������������������������������������������������������������������������������������������������������������������������� 228
Implementing the Controller As a Data Source and Delegate������������������������������������������������������������� 230

Implementing a Multicomponent Picker���������������������������������������������������������������������� 234


Building the View�������������������������������������������������������������������������������������������������������������������������������� 234
Implementing the Controller��������������������������������������������������������������������������������������������������������������� 235

Implementing Dependent Components������������������������������������������������������������������������ 237


Creating a Simple Game with a Custom Picker������������������������������������������������������������ 245
Preparing the View Controller������������������������������������������������������������������������������������������������������������� 245
Building the View�������������������������������������������������������������������������������������������������������������������������������� 246
Implementing the Controller��������������������������������������������������������������������������������������������������������������� 247
Final Details���������������������������������������������������������������������������������������������������������������������������������������� 251

Final Spin��������������������������������������������������������������������������������������������������������������������� 254



■Chapter 8: Introduction to Table Views������������������������������������������������������������� 255
Table View Basics��������������������������������������������������������������������������������������������������������� 256
Table Views and Table View Cells������������������������������������������������������������������������������������������������������� 256
Grouped and Plain Tables������������������������������������������������������������������������������������������������������������������� 258

Implementing a Simple Table��������������������������������������������������������������������������������������� 259


Designing the View����������������������������������������������������������������������������������������������������������������������������� 259
Writing the Controller������������������������������������������������������������������������������������������������������������������������� 262
Adding an Image��������������������������������������������������������������������������������������������������������������������������������� 265
Using Table View Cell Styles��������������������������������������������������������������������������������������������������������������� 267
Setting the Indent Level���������������������������������������������������������������������������������������������������������������������� 269
xii Contents

Handling Row Selection���������������������������������������������������������������������������������������������������������������������� 270


Changing the Font Size and Row Height�������������������������������������������������������������������������������������������� 273

Customizing Table View Cells��������������������������������������������������������������������������������������� 275


Adding Subviews to the Table View Cell �������������������������������������������������������������������������������������������� 276
Creating a UITableViewCell Subclass�������������������������������������������������������������������������������������������������� 277
Loading a UITableViewCell from a Nib������������������������������������������������������������������������������������������������ 281
Grouped and Indexed Sections������������������������������������������������������������������������������������� 287
Building the View�������������������������������������������������������������������������������������������������������������������������������� 287
Importing the Data������������������������������������������������������������������������������������������������������������������������������ 288
Implementing the Controller��������������������������������������������������������������������������������������������������������������� 288
Adding an Index���������������������������������������������������������������������������������������������������������������������������������� 292

Implementing a Search Bar������������������������������������������������������������������������������������������ 293


How Many Tables?: View Debugging���������������������������������������������������������������������������� 302
Putting It All on the Table���������������������������������������������������������������������������������������������� 306

■Chapter 9: Navigation Controllers and Table Views������������������������������������������� 307
Navigation Controller Basics���������������������������������������������������������������������������������������� 308
Stacky Goodness�������������������������������������������������������������������������������������������������������������������������������� 308
A Stack of Controllers������������������������������������������������������������������������������������������������������������������������� 308

Fonts: A Simple Font Browser�������������������������������������������������������������������������������������� 310


Meet the Subcontrollers��������������������������������������������������������������������������������������������������������������������� 311
The Fonts Application’s Skeleton�������������������������������������������������������������������������������������������������������� 314

Creating the Root View Controller�������������������������������������������������������������������������������� 317


Initial Storyboard Setup������������������������������������������������������������������������������������������������ 321
First Subcontroller: The Font List View������������������������������������������������������������������������� 322
Storyboarding the Font List���������������������������������������������������������������������������������������������������������������� 324
Making the Root View Controller Prepare for Segues������������������������������������������������������������������������� 326

Creating the Font Sizes View Controller����������������������������������������������������������������������� 327


Storyboarding the Font Sizes View Controller������������������������������������������������������������������������������������ 328
Making the Font List View Controller Prepare for Segues������������������������������������������������������������������ 329
Contents xiii

Creating the Font Info View Controller�������������������������������������������������������������������������� 329


Storyboarding the Font Info View Controller��������������������������������������������������������������������������������������� 330
Setting Up Constraints������������������������������������������������������������������������������������������������������������������������ 333
Adapting the Font List View Controller for Multiple Segues��������������������������������������������������������������� 333
My Favorite Fonts������������������������������������������������������������������������������������������������������������������������������� 334

Table View Niceties������������������������������������������������������������������������������������������������������ 335


Implementing Swipe-to-Delete���������������������������������������������������������������������������������������������������������� 336
Implementing Drag-to-Reorder���������������������������������������������������������������������������������������������������������� 338

Breaking the Tape��������������������������������������������������������������������������������������������������������� 340



■Chapter 10: Collection View and Stack View����������������������������������������������������� 341
Creating the DialogViewer Project�������������������������������������������������������������������������������� 342
Defining Custom Cells�������������������������������������������������������������������������������������������������� 343
Configuring the View Controller������������������������������������������������������������������������������������ 346
Providing Content Cells������������������������������������������������������������������������������������������������ 347
Making the Layout Flow����������������������������������������������������������������������������������������������� 349
Providing Header Views������������������������������������������������������������������������������������������������ 352
Working with UIStackView������������������������������������������������������������������������������������������� 354
Creating a Vertical Stack�������������������������������������������������������������������������������������������������������������������� 356
Adding a Horizontal Stack������������������������������������������������������������������������������������������������������������������ 364
Completing the Application����������������������������������������������������������������������������������������������������������������� 369


■Chapter 11: Using Split Views and Popovers����������������������������������������������������� 371
Building Master-Detail Applications with UISplitViewController����������������������������������� 375
The Storyboard Defines the Structure������������������������������������������������������������������������������������������������ 377
The Code Defines the Functionality���������������������������������������������������������������������������������������������������� 379
How the Master-Detail Template Application Works��������������������������������������������������������������������������� 383

Here Come the Presidents�������������������������������������������������������������������������������������������� 386


Creating Your Own Popover������������������������������������������������������������������������������������������ 394
Split Views on the iPhone��������������������������������������������������������������������������������������������� 401
Split Views on the iPhone 6/6s Plus��������������������������������������������������������������������������������������������������� 403
Getting the iPhone 6/6s Plus Behavior on All iPhones������������������������������������������������������������������������ 404
xiv Contents

Customizing the Split View������������������������������������������������������������������������������������������� 408


Time to Wrap Up and Split�������������������������������������������������������������������������������������������� 410

■Chapter 12: Application Settings and User Defaults������������������������������������������ 411
Getting to Know Your Settings Bundle�������������������������������������������������������������������������� 411
The Bridge Control Application������������������������������������������������������������������������������������� 413
Creating the Project���������������������������������������������������������������������������������������������������������������������������� 418
Working with the Settings Bundle������������������������������������������������������������������������������������������������������ 419
Reading Settings in Our Application��������������������������������������������������������������������������������������������������� 439
Changing Defaults from Our Application�������������������������������������������������������������������������������������������� 443
Registering Default Values������������������������������������������������������������������������������������������������������������������ 446
Keeping It Real����������������������������������������������������������������������������������������������������������������������������������� 447

Switching to the Settings Application�������������������������������������������������������������������������� 450


Beam Me Up, Scotty����������������������������������������������������������������������������������������������������� 451

■Chapter 13: Basic Data Persistence������������������������������������������������������������������ 453
Your Application’s Sandbox������������������������������������������������������������������������������������������ 454
Getting the Documents and Library Directories���������������������������������������������������������������������������������� 456
Getting the tmp Directory������������������������������������������������������������������������������������������������������������������� 458

File-Saving Strategies�������������������������������������������������������������������������������������������������� 458


Single-File Persistence����������������������������������������������������������������������������������������������������������������������� 458
Multiple-File Persistence�������������������������������������������������������������������������������������������������������������������� 459

Using Property Lists����������������������������������������������������������������������������������������������������� 459


Property List Serialization������������������������������������������������������������������������������������������������������������������� 459
The First Version of the Persistence Application�������������������������������������������������������������������������������� 461

Archiving Model Objects����������������������������������������������������������������������������������������������� 467


Conforming to NSCoding�������������������������������������������������������������������������������������������������������������������� 467
Implementing NSCopying������������������������������������������������������������������������������������������������������������������� 469
Archiving and Unarchiving Data Objects�������������������������������������������������������������������������������������������� 470
The Archiving Application������������������������������������������������������������������������������������������������������������������� 472
Contents xv

Using iOS’s Embedded SQLite3������������������������������������������������������������������������������������ 475


Creating or Opening the Database������������������������������������������������������������������������������������������������������ 476
Using Bind Variables��������������������������������������������������������������������������������������������������������������������������� 477
The SQLite3 Application���������������������������������������������������������������������������������������������������������������������� 478

Using Core Data������������������������������������������������������������������������������������������������������������ 485


Entities and Managed Objects������������������������������������������������������������������������������������������������������������ 487
The Core Data Application������������������������������������������������������������������������������������������������������������������ 491

Persistence Rewarded������������������������������������������������������������������������������������������������� 501



■Chapter 14: Documents and iCloud������������������������������������������������������������������� 503
Managing Document Storage with UIDocument���������������������������������������������������������� 504
Building TinyPix���������������������������������������������������������������������������������������������������������������������������������� 504
Creating TinyPixDocument������������������������������������������������������������������������������������������������������������������ 505
Code Master��������������������������������������������������������������������������������������������������������������������������������������� 508
Initial Storyboarding��������������������������������������������������������������������������������������������������������������������������� 515
Creating TinyPixView�������������������������������������������������������������������������������������������������������������������������� 518
Storyboard Detailing��������������������������������������������������������������������������������������������������������������������������� 522

Adding iCloud Support�������������������������������������������������������������������������������������������������� 527


Creating a Provisioning Profile����������������������������������������������������������������������������������������������������������� 527
How to Query�������������������������������������������������������������������������������������������������������������������������������������� 531
Save Where?��������������������������������������������������������������������������������������������������������������������������������������� 533
Storing Preferences on iCloud������������������������������������������������������������������������������������������������������������ 533

What We Didn’t Cover��������������������������������������������������������������������������������������������������� 536



■Chapter 15: Grand Central Dispatch, Background Processing, and You������������ 539
Grand Central Dispatch������������������������������������������������������������������������������������������������ 539
Introducing SlowWorker����������������������������������������������������������������������������������������������� 540
Threading Basics���������������������������������������������������������������������������������������������������������� 544
Units of Work���������������������������������������������������������������������������������������������������������������� 545
GCD: Low-Level Queuing���������������������������������������������������������������������������������������������� 545
Improving SlowWorker����������������������������������������������������������������������������������������������������������������������� 547
xvi Contents

Background Processing����������������������������������������������������������������������������������������������� 553


Application Life Cycle������������������������������������������������������������������������������������������������������������������������� 554
State-Change Notifications����������������������������������������������������������������������������������������������������������������� 555
Creating State Lab������������������������������������������������������������������������������������������������������������������������������ 556
Exploring Execution States����������������������������������������������������������������������������������������������������������������� 557
Using Execution State Changes���������������������������������������������������������������������������������������������������������� 559
Handling the Inactive State���������������������������������������������������������������������������������������������������������������� 560
Handling the Background State���������������������������������������������������������������������������������������������������������� 564

Grand Central Dispatch, Over and Out�������������������������������������������������������������������������� 573



■Chapter 16: Drawing with Core Graphics���������������������������������������������������������� 575
Paint the World������������������������������������������������������������������������������������������������������������� 575
The Quartz 2D Approach to Drawing���������������������������������������������������������������������������� 576
Quartz 2D’s Graphics Contexts����������������������������������������������������������������������������������������������������������� 576
The Coordinate System���������������������������������������������������������������������������������������������������������������������� 577
Specifying Colors�������������������������������������������������������������������������������������������������������������������������������� 578
Drawing Images in Context����������������������������������������������������������������������������������������������������������������� 580
Drawing Shapes: Polygons, Lines, and Curves����������������������������������������������������������������������������������� 581
Quartz 2D Tool Sampler: Patterns, Gradients, and Dash Patterns������������������������������������������������������� 581

The QuartzFun Application������������������������������������������������������������������������������������������� 583


Setting Up the QuartzFun Application������������������������������������������������������������������������������������������������� 584
Adding Quartz 2D Drawing Code�������������������������������������������������������������������������������������������������������� 593
Optimizing the QuartzFun Application������������������������������������������������������������������������������������������������ 598

Drawing to a Close������������������������������������������������������������������������������������������������������� 602



■Chapter 17: Getting Started with SpriteKit�������������������������������������������������������� 603
Simple Beginnings������������������������������������������������������������������������������������������������������� 603
Initial Scene Customization���������������������������������������������������������������������������������������������������������������� 611

Player Movement��������������������������������������������������������������������������������������������������������� 616


Adding the Player to the Scene���������������������������������������������������������������������������������������������������������� 617
Handling Touches: Player Movement�������������������������������������������������������������������������������������������������� 618
Geometry Calculations������������������������������������������������������������������������������������������������������������������������ 619
Wobbly Bits����������������������������������������������������������������������������������������������������������������������������������������� 620
Contents xvii

Creating Your Enemies������������������������������������������������������������������������������������������������� 621


Putting Enemies in the Scene�������������������������������������������������������������������������������������� 622
Start Shooting�������������������������������������������������������������������������������������������������������������� 624
Defining Your Physics Categories������������������������������������������������������������������������������������������������������� 625
Creating the BulletNode Class������������������������������������������������������������������������������������������������������������ 625
Applying Physics��������������������������������������������������������������������������������������������������������������������������������� 626
Adding Bullets to the Scene��������������������������������������������������������������������������������������������������������������� 627

Attacking Enemies with Physics���������������������������������������������������������������������������������� 629


Finishing Levels������������������������������������������������������������������������������������������������������������ 631
Keeping Tabs on the Enemies������������������������������������������������������������������������������������������������������������� 631
Transitioning to the Next Level����������������������������������������������������������������������������������������������������������� 632

Customizing Collisions������������������������������������������������������������������������������������������������� 633


Adding a Class Extension to SKNode�������������������������������������������������������������������������������������������������� 635
Adding Custom Collision Behavior to Enemies����������������������������������������������������������������������������������� 636
Showing Accurate Player Lives���������������������������������������������������������������������������������������������������������� 637

Spicing Things Up with Particles���������������������������������������������������������������������������������� 638


Your First Particle������������������������������������������������������������������������������������������������������������������������������� 639
Putting Particles into the Scene��������������������������������������������������������������������������������������������������������� 642

The End Game�������������������������������������������������������������������������������������������������������������� 644


At Last, a Beginning: Create a StartScene�������������������������������������������������������������������� 647
A Sound Is Worth a Thousand Pictures������������������������������������������������������������������������� 650
Making the Game a Little Harder: Force Fields������������������������������������������������������������ 651
Game Over�������������������������������������������������������������������������������������������������������������������� 654

■Chapter 18: Taps, Touches, and Gestures���������������������������������������������������������� 655
Multitouch Terminology������������������������������������������������������������������������������������������������ 656
The Responder Chain��������������������������������������������������������������������������������������������������� 656
Responding to Events������������������������������������������������������������������������������������������������������������������������� 657
Forwarding an Event: Keeping the Responder Chain Alive����������������������������������������������������������������� 658

The Multitouch Architecture����������������������������������������������������������������������������������������� 658


The Four Touch Notification Methods��������������������������������������������������������������������������� 659
xviii Contents

The TouchExplorer Application������������������������������������������������������������������������������������� 660


The Swipes Application������������������������������������������������������������������������������������������������ 665
Using Touch Events to Detect Swipes������������������������������������������������������������������������������������������������� 666
Automatic Gesture Recognition���������������������������������������������������������������������������������������������������������� 669
Implementing Multiple Swipes����������������������������������������������������������������������������������������������������������� 671

Detecting Multiple Taps������������������������������������������������������������������������������������������������ 673


Detecting Pinch and Rotation��������������������������������������������������������������������������������������� 677
Defining Custom Gestures�������������������������������������������������������������������������������������������� 681
The CheckPlease Application�������������������������������������������������������������������������������������������������������������� 682
The CheckPlease Touch Methods������������������������������������������������������������������������������������������������������� 684

Garçon? Check, Please!������������������������������������������������������������������������������������������������ 687



■Chapter 19: Where Am I? Finding Your Way with Core Location and Map Kit����689
The Location Manager�������������������������������������������������������������������������������������������������� 690
Setting the Desired Accuracy������������������������������������������������������������������������������������������������������������� 690
Setting the Distance Filter������������������������������������������������������������������������������������������������������������������ 691
Getting Permission to Use Location Services������������������������������������������������������������������������������������� 691
Starting the Location Manager����������������������������������������������������������������������������������������������������������� 691
Using the Location Manager Wisely���������������������������������������������������������������������������������������������������� 692

The Location Manager Delegate����������������������������������������������������������������������������������� 692


Getting Location Updates������������������������������������������������������������������������������������������������������������������� 692
Getting Latitude and Longitude Using CLLocation������������������������������������������������������������������������������ 692
Error Notifications������������������������������������������������������������������������������������������������������������������������������� 695

Trying Out Core Location���������������������������������������������������������������������������������������������� 696


Using Location Manager Updates������������������������������������������������������������������������������������������������������� 702

Visualizing Your Movement on a Map��������������������������������������������������������������������������� 704


Changing Location Service Permissions�������������������������������������������������������������������������������������������� 708

Wherever You Go, There You Are����������������������������������������������������������������������������������� 710



■Chapter 20: Whee! Gyro and Accelerometer!���������������������������������������������������� 711
Accelerometer Physics������������������������������������������������������������������������������������������������� 711
Don’t Forget Rotation��������������������������������������������������������������������������������������������������� 712
Contents xix

Core Motion and the Motion Manager�������������������������������������������������������������������������� 713


Event-Based Motion��������������������������������������������������������������������������������������������������������������������������� 713
Proactive Motion Access�������������������������������������������������������������������������������������������������������������������� 718
Gyroscope and Attitude Results���������������������������������������������������������������������������������������������������������� 721
Accelerometer Results����������������������������������������������������������������������������������������������������������������������� 721

Detecting Shakes��������������������������������������������������������������������������������������������������������� 723


Baked-In Shaking������������������������������������������������������������������������������������������������������������������������������� 723
Shake and Break�������������������������������������������������������������������������������������������������������������������������������� 724

Accelerometer As Directional Controller���������������������������������������������������������������������� 727


Rolling Marbles����������������������������������������������������������������������������������������������������������������������������������� 728
Writing the Ball View�������������������������������������������������������������������������������������������������������������������������� 730
Calculating Ball Movement����������������������������������������������������������������������������������������������������������������� 732

Rolling On��������������������������������������������������������������������������������������������������������������������� 735



■Chapter 21: The Camera and Photo Library������������������������������������������������������� 737
Using the Image Picker and UIImagePickerController�������������������������������������������������� 737
Using the Image Picker Controller������������������������������������������������������������������������������������������������������ 737
Implementing the Image Picker Controller Delegate�������������������������������������������������������������������������� 740

Road Testing the Camera and Library�������������������������������������������������������������������������� 741


Designing the Interface���������������������������������������������������������������������������������������������������������������������� 742
Implementing the Camera View Controller����������������������������������������������������������������������������������������� 744

It’s a Snap!������������������������������������������������������������������������������������������������������������������� 748



■Chapter 22: Application Localization����������������������������������������������������������������� 749
Localization Architecture���������������������������������������������������������������������������������������������� 749
Strings Files����������������������������������������������������������������������������������������������������������������� 751
What’s in a Strings File?��������������������������������������������������������������������������������������������������������������������� 751
The Localized String Function������������������������������������������������������������������������������������������������������������ 752

Real-World iOS: Localizing Your Application����������������������������������������������������������������� 753


Setting Up LocalizeMe������������������������������������������������������������������������������������������������������������������������ 754
Trying Out LocalizeMe������������������������������������������������������������������������������������������������������������������������ 757
Localizing the Project������������������������������������������������������������������������������������������������������������������������� 759
xx Contents

Localizing the Storyboard������������������������������������������������������������������������������������������������������������������� 762


Generating and Localizing a Strings File�������������������������������������������������������������������������������������������� 768
Localizing the App Display Name������������������������������������������������������������������������������������������������������� 774

Adding Another Localization����������������������������������������������������������������������������������������� 775


Auf Wiedersehen���������������������������������������������������������������������������������������������������������� 776

■Appendix A: A Swift Introduction to Swift��������������������������������������������������������� 777
Swift Basics����������������������������������������������������������������������������������������������������������������� 777
Playgrounds, Comments, Variables, and Constants���������������������������������������������������������������������������� 778
Predefined Types, Operators, and Control Statements����������������������������������������������������������������������� 782
Arrays, Ranges, and Dictionaries�������������������������������������������������������������������������������������������������������� 794
Optionals��������������������������������������������������������������������������������������������������������������������������������������������� 800
Control Statements����������������������������������������������������������������������������������������������������������������������������� 806
Functions and Closures���������������������������������������������������������������������������������������������������������������������� 811
Error Handling������������������������������������������������������������������������������������������������������������������������������������� 817

Classes and Structures������������������������������������������������������������������������������������������������ 823


Structures������������������������������������������������������������������������������������������������������������������������������������������� 824
Classes����������������������������������������������������������������������������������������������������������������������������������������������� 826
Properties������������������������������������������������������������������������������������������������������������������������������������������� 827
Methods���������������������������������������������������������������������������������������������������������������������������������������������� 830
Optional Chaining������������������������������������������������������������������������������������������������������������������������������� 831
Subclassing and Inheritance�������������������������������������������������������������������������������������������������������������� 832
Protocols��������������������������������������������������������������������������������������������������������������������������������������������� 836
Extensions������������������������������������������������������������������������������������������������������������������������������������������ 838

To Swiftly Go...�������������������������������������������������������������������������������������������������������������� 838

Index��������������������������������������������������������������������������������������������������������������������� 839

www.allitebooks.com
About the Authors
Dave Mark is a longtime Mac developer and author who has
written a number of books on Mac and iOS development,
including Beginning iOS 6 Development (Apress, 2013),
More iOS 6 Development (Apress, 2013), Learn C on the Mac
(Apress, 2013), Ultimate Mac Programming (Wiley, 1995), and
the Macintosh Programming Primer series (Addison-Wesley,
1992). Dave was one of the founders of MartianCraft, an iOS
and Android development house. Dave loves the water and
spends as much time as possible on it, in it, or near it. He lives
with his wife and three children in Virginia. On Twitter, he’s
@davemark.

Kim Topley is a software engineer with over 30 years of


experience ranging from mainframe microcode and the UNIX
kernel to graphical user interfaces and mobile applications.
He is the author of Learn WatchKit for iOS and of five books
on various aspects of Java and JavaFX. He has been working
with iOS since reading one of the first books published on the
subject—the first edition of Beginning iPhone Development.

xxi
xxii About the Authors

Jack Nutting has been using Cocoa since the olden days, long
before it was even called Cocoa. He has used Cocoa and its
predecessors to develop software for a wide range of industries
and applications, including gaming, graphic design, online
digital distribution, telecommunications, finance, publishing,
and travel. Jack has written several books on iOS and Mac
development, including Beginning iOS 6 Development (Apress,
2013), Learn Cocoa on the Mac (Apress, 2013), and Beginning
iPad Development for iPhone Developers (Apress, 2010).
Besides writing software and books, he also leads developer
training and blogs from time to time at www.nuthole.com. He’s
@jacknutting on Twitter.

Fredrik Olsson has been using Cocoa since Mac OS X 10.1


and for iPhone since the unofficial toolchain. He has had
a long and varied career, ranging from real-time assembly
to enterprise Java. He is passionate about Objective-C for
its elegance, Cocoa frameworks for its clarity, and both for
creating a greater whole than their parts. When away from a
keyboard, Fredrik has spoken at conferences and led developer
training. You’ll find Fredrik on Twitter as @peylow.

Jeff LaMarche is a Mac and an iOS developer with more than 20


years of programming experience. Jeff has written a number of
iOS and Mac development books, including Beginning iOS 6
Development (Apress, 2013) and More iOS 6 Development
(Apress, 2013). Jeff is a principal at MartianCraft, an iOS and
Android development house. He has written about Cocoa and
Objective-C for MacTech magazine, as well as articles for Apple’s
developer web site. Jeff also writes about iOS development for
his widely read blog at www.iphonedevelopment.blogspot.com.
He can be found on Twitter as @jeff_lamarche.
About the Technical
Reviewer
Bruce Wade is the founder of Warply Designed Inc.
(www.warplydesigned.com), a company specializing in using
game technology for real-world applications. He has more
than 16 years of software development experience with a
strong focus on 2D/3D animation and interactive applications,
primarily using Apple technology.

xxiii
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 9,
Xcode 7, 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!

1
2 CHAPTER 1: Welcome to the Swift Jungle

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 Yosemite (OS X 10.10), El Capitan (OS X 10.11) or
later. Any recent Intel-based Macintosh computer—laptop or desktop—should work just
fine. Of course, as well as the hardware, you’ll need the software. You can learn how to
develop iOS applications and get the software tools that you’ll need as long as you have an
Apple ID—if you own an iPhone, iPad or iPod then you’ve almost certainly already got an
Apple ID, but if you don’t, then just visit https://appleid.apple.com/account and create
one. Once you’ve done that, navigate to https://developer.apple.com/resources. 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


CHAPTER 1: Welcome to the Swift Jungle 3

Click on iOS to go to the main resources page for the current production release and (if there
is one) the current beta release of iOS. Here, 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. Be sure to scroll to the bottom of the page and check out the links
to the Documentation and Videos sections of the web site. You’ll also find a link to the Apple
Developer Forums, where you can follow discussions on a wide variety of topics covering
the whole iOS platform, as well as OS X and watchOS (the operating system for the Apple
Watch), although you’ll need to be a registered Apple developer to post to the forums.
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 the current beta release of Xcode by following the Xcode link from the
developer resources page in Figure 1-1. If you prefer to use the latest production release,
you’ll find it in 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: unless you really want to work with the most recent development
tools and platform SDK, 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 9 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.

Developer Options
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. To test applications that use those features, you’ll 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.
4 CHAPTER 1: Welcome to the Swift Jungle

Previous versions of Xcode required you to register for the Apple developer program
(which is not free) to install your applications on a real iPhone or other device. Fortunately,
this has changed. Xcode 7 allows you to test applications on real hardware, albeit with
some limitations that we’ll cover as we go along, without purchasing an Apple developer
membership. That means you can run most of the examples in this book on your iPhone
or iPad for free! However, the free option 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 applications
via Apple’s iOS and Mac App Stores. Your membership lets you develop
and distribute applications for iOS, watchOS and OS X.
 The Enterprise program costs $299/year. It is designed for companies
developing proprietary, in-house iOS applications.
For more details on these programs, visit https://developer.apple.com/programs. If you
are an independent developer, you can definitely get away with just buying the standard
program membership and you don’t have to do that until you need to run an application that
uses a feature such as iCloud that requires a paid membership, you want to post a question
to the Apple Developer forums or you are ready to deploy your application to the App Store.
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.

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 Playground feature in Xcode that makes it easy to try out the features
of this exciting language. If you’d like to learn more about Swift after reading the material
in the Appendix, the best way to do so is to go directly to the source and read The Swift
Programming Language, which is Apple’s own guide and reference to the language. You can
get it from the iBooks store or from the iOS developer site at https://developer.apple.com/
library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/index.html.
CHAPTER 1: Welcome to the Swift Jungle 5

You also 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 of what you’ll find 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, it’s usually the case that 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). In iOS 9,
Apple added the ability for two applications to run in the foreground and share the screen,
but for that the user needs to have one of the more recent iPads. We’ll talk about that
feature, which Apple calls Multitasking, in Chapter 11.
When your application isn’t active or running in the background, it doesn’t receive any
attention whatsoever from the CPU. 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, unless your user has activated the Multitasking feature, in which case your
application may have to give up some of the screen to another application.
6 CHAPTER 1: Welcome to the Swift Jungle

Limited Access
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/6s 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 9 at the time of writing.
CHAPTER 1: Welcome to the Swift Jungle 7

Table 1-1. iOS Device Screen Sizes

Device Hardware Size Software Size Scaling Factor


iPhone 4s 640 × 960 320 × 480 2x
iPhone 5 and 5s 640 × 1136 320 × 568 2x
iPhone 6/6s 750 × 1334 375 × 667 2x
iPhone 6/6s Plus 1080 × 1920 414 × 736 3x
iPad 2 and iPad mini 768 × 1024 768 × 1024 1x
iPad Air, iPad Air 2, iPad Retina, and iPad mini Retina 1536 × 2048 768 × 1024 2x
iPad Pro 2732 × 2048 1366 × 1024 2x

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/6s 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/6s, 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/6s 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/6s 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.

www.allitebooks.com
8 CHAPTER 1: Welcome to the Swift Jungle

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/6s,
iPhone 6/6s Plus, iPad Air, iPad Air 2, 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.
CHAPTER 1: Welcome to the Swift Jungle 9

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. Chapter 10 also covers the new (in
iOS 9) UIStackView class, which makes it easy to display components
arranged in a single row or a single column, which is something that
you’ll probably need to do more often than you would expect.
10 CHAPTER 1: Welcome to the Swift Jungle

 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. This chapter also discusses the new iOS 9 Multitasking feature,
which lets an iPad user work with two applications on the screen at the
same time.
 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.
CHAPTER 1: Welcome to the Swift Jungle 11

 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 2 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! iOS 9 and Xcode 7 contain
a lot of new enhancements. We’ve been hard at work updating the book to cover the new
technologies in both iOS 9 and Xcode 7 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 and is likely to remain so for some time to
come. 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. As a result, it is possible that example code that
compiled and worked with the version of Xcode that was current when this book was
published no longer works by the time you read it. Xcode 6.0 shipped with Swift version 1,
Xcode 6.3 had Swift version 1.2 and Xcode 7 introduced Swift 2. The code in this book was
written for and tested with Xcode 7 and Swift 2 and most of the examples can’t be compiled
with Xcode 6, although you can deploy Swift applications written with Xcode 7 to iOS 8 and
iOS 7 provided, of course, that you don’t try to use features that were introduced in later
versions of the platform.

Tip Swift 2 added a new feature that makes it easy to check whether features that you need are
available on the platform that your application is running on. You’ll find the details in the appendix.
12 CHAPTER 1: Welcome to the Swift Jungle

If you find that some of the example source 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 version. If after doing this you are still 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’ve already downloaded and installed Xcode, turn the page. If not, get to it!
Got it? Good. Then let’s go!
Chapter 2
Appeasing the Tiki Gods
As you’re probably well aware, it has become something of a tradition to call the first project
in any book on programming, “Hello, World.” We considered breaking with this tradition, but
were scared that the Tiki gods would inflict some painful retribution on us for such a gross
breach of etiquette. So, let’s do it by the book, shall we?
In this chapter, we’re going to use Xcode to create a small iOS application that will display
the text, “Hello, World!” We’ll look at what’s involved in creating an iOS application project
in Xcode, work through the specifics of using Xcode’s Interface Builder to design our
application’s user interface, and then run our application on the iOS simulator and on a
real device. After that, we’ll give our application an icon to make it feel more like a real iOS
application.
We have a lot to do here, so let’s get going.

Setting Up Your Project in Xcode


By now, you should have Xcode and the iOS SDK installed on your machine. You should
also download the book’s source code archive from the Apress web site (http://apress.
com). While you’re at it, take a look at the book forums at http://forum.learncocoa.org/.
The book forums are a great place to discuss iOS development, get your questions
answered, and meet up with like-minded people.

Note Even though you have the complete set of project files at your disposal in this book’s source
code archive, you’ll get more out of the book if you create each project by hand, rather than simply
running the version you downloaded. By doing that, you’ll gain familiarity and expertise working
with the various application development tools.
There’s no substitute for actually creating applications; software development is not a spectator
sport.

13
14 CHAPTER 2: Appeasing the Tiki Gods

The project we’re going to build in this chapter is contained in the 02 - Hello World folder of
the source code archive.
Before we can start, we need to launch Xcode, the tool that we’ll use to do most of what
we do in this book. After downloading it from the Mac App Store or the Apple Developer
site, you’ll find it installed in the /Applications folder, as with most Mac applications. You’ll
be using Xcode a lot, so you might want to consider dragging it to your dock so you’ll have
ready access to it.
If this is your first time using Xcode, don’t worry; we’ll walk you through every step involved
in creating a new project. If you’re already an old hand but haven’t worked with Xcode 7, you
may find that some things have changed (mostly for the better, we think).
When you first launch Xcode, you’ll be presented with a welcome window like the one
shown in Figure 2-1. From here, you can choose to create a new project, connect to a
version-control system to check out an existing project, or select from a list of recently
opened projects. The welcome window gives you a nice starting point, covering some of the
most common tasks you’re likely to want to do after launching Xcode. All of these actions
can be accessed through the menu as well, so close the window, and we’ll proceed. If you
would rather not see this window in the future, just uncheck the Show this window when
Xcode launches check box at the bottom of the window before closing it.

Figure 2-1. The Xcode welcome window

Create a new project by selecting New ➤ Project… from the File menu (or by pressing
 N). A new project window will open, showing you the project template selection sheet
(see Figure 2-2). From this sheet, you’ll choose a project template to use as a starting point
CHAPTER 2: Appeasing the Tiki Gods 15

for building your application. The pane on the left side of the sheet is divided into two main
sections: iOS and OS X. Since we’re building an iOS application, select Application in the
iOS section to reveal the iOS application templates.

Figure 2-2. The project template selection sheet lets you select from various templates when creating a new project

Each of the icons shown in the upper-right pane in Figure 2-2 represents a separate project
template that can be used as a starting point for your iOS applications. The icon labeled
Single View Application is the simplest template and the one we’ll be using for the first
several chapters. The other templates provide additional code and/or resources needed to
create common iPhone and iPad application interfaces, as you’ll see in later chapters.
Click the Single View Application icon (see Figure 2-2), and then click the Next button. You’ll
see the project options sheet, which should look like Figure 2-3. On this sheet, you need to
specify the Product Name and Company Identifier for your project. Xcode will combine these
to generate a unique bundle identifier for your app. You’ll also see a field that lets you enter an
Organization Name, which Xcode will use to automatically insert a copyright notice into every
source code file you create. Name your product Hello World and enter an organization name and
identifier in the Organization Name and Organization Identifier fields, as shown in Figure 2-3.
Don’t use the same name and identifier as the ones shown in Figure 2-3—for reasons that
you’ll see when we try to run this application on a real device at the end of the chapter, you’ll
need to choose an identifier that’s unique to you (or your company).
16 CHAPTER 2: Appeasing the Tiki Gods

Figure 2-3. Selecting a product name and organization identifier for your project

The Language field lets you select the programming language that you want to use. You
can choose between Objective-C and Swift, but since all of the examples in the book are in
Swift, the appropriate choice here is, of course, Swift.
We also need to specify the Devices. In other words, Xcode wants to know if we’re building
an app for the iPhone and iPod touch, if we’re building an app for the iPad, or if we’re
building a universal application that will run on all iOS devices. Select iPhone for the
Devices if it’s not already selected. This tells Xcode that we’ll be targeting this particular app
at the iPhone and iPod touch, which have roughly the same screen size and form factor. For
the first few chapters of the book, we’ll be using the iPhone device, but don’t worry—we’ll
cover the iPad also.
Leave the Core Data check box unchecked—we’ll make use of it in Chapter 13. We’ll also
leave the Include Unit Tests and Include UI Tests check boxes unchecked. Xcode has very
good support for testing of your applications, but that’s outside the scope of this book, so
we don’t need Xcode to include support for them in our project. Click Next again, and you’ll
be asked where to save your new project using a standard save sheet (see Figure 2-4). If you
haven’t already done so, jump over to the Finder, create a new master directory for these
book projects, and then return to Xcode and navigate into that directory. Before you click the
Create button, take note of the Source Control check box. We won’t be talking about Git in
this book, but Xcode includes some support for using Git and other kinds of source control
CHAPTER 2: Appeasing the Tiki Gods 17

management (SCM) tools. If you are already familiar with Git and want to use it, enable this
check box; otherwise, feel free to turn it off.

Note Source Control Management (SCM) is a technique for keeping track of changes made to an
application’s source code and resources while it’s being built. It also facilitates multiple developers
working on the same application at the same time by providing tools to resolve conflicts when they
arise. Xcode has built-in support for Git, one of the most popular SCM systems in use today. We
won’t be dealing with source control issues in this book, so it’s up to you to enable it or disable it,
whichever works for you.

After choosing whether to create a Git repository, create the new project by clicking the
Create button.

Figure 2-4. Saving your project in a project folder on your hard drive
18 CHAPTER 2: Appeasing the Tiki Gods

The Xcode Project Window


After you dismiss the save sheet, Xcode will create and then open your project. You will
see a new project window (see Figure 2-5). There’s a lot of information crammed into this
window, and it’s where you will be spending a lot of your iOS development time.

Figure 2-5. The Hello World project in Xcode

Even if you are an old hand with earlier versions of Xcode, you may still benefit from reading
through this section, since Apple has a habit of rearranging things and making improvements
from release to release. Let’s take a quick tour.

The Toolbar
The top of the Xcode project window is called the toolbar (see Figure 2-6). On the left side
of the toolbar are controls to start and stop running your project, as well as a pop-up menu
to select the scheme you want to run. A scheme brings together target and build settings,
and the toolbar pop-up menus lets you select a specific setup quickly and easily.
CHAPTER 2: Appeasing the Tiki Gods 19

Figure 2-6. The Xcode toolbar

The big box in the middle of the toolbar is the Activity View. As its name implies, the activity
view displays any actions or processes that are currently happening. For example, when you
run your project, the activity view gives you a running commentary on the various steps it’s
taking to build your application. If you encounter any errors or warnings, that information
is displayed here, as well. If you click the warning or error, you’ll go directly to the Issue
Navigator, which provides more information about the warning or error, as described in the
next section.
On the right side of the toolbar are two sets of buttons. The left set lets you switch between
three different editor configurations:
 The Editor Area gives you a single pane dedicated to editing a file or
project-specific configuration values.
 The incredibly powerful Assistant Editor splits the Editor Area into two
panes, left and right. The pane on the right is generally used to display
a file that relates to the file on the left, or that you might need to refer
to while editing the file on the left. You can manually specify what goes
into each pane, or you can let Xcode decide what’s most appropriate
for the task at hand. For example, if you’re designing your user interface
on the left, Xcode will show you the code that the user interface is
able to interact with on the right. You’ll see the Assistant Editor at work
throughout the book.
 The Version Editor button converts the editor pane into a time
machine–like comparison view that works with version control systems
like Git. You can compare the current version of a source file with a
previously committed version or compare any two earlier versions with
each other.
To the right of the editor buttons is a set of toggle buttons that show and hide large panes
on the left and right sides of the editor view, as well as the debug area at the bottom of the
window. Click each of those buttons a few times to see these panes in action. You’ll learn
more about how these are used soon.
20 CHAPTER 2: Appeasing the Tiki Gods

The Navigator
Just below the toolbar, on the left side of the project window, is the Navigator. The
Navigator offers eight views that show you different aspects of your project. Click each of
the icons at the top of the navigator to switch among the following navigators, going from
left to right:
 Project Navigator: This view contains a list of files in your project (see
Figure 2-7). You can store references to everything you expect—from
source code files to artwork, data models, property list (or .plist) files
(discussed in the “A Closer Look at Our Project” section later in this
chapter), and even other project files. By storing multiple projects in a
single workspace, those projects can easily share resources. If you click
any file in the navigator view, that file will display in the Editor Area. In
addition to viewing the file, you can also edit it (if it’s a file that Xcode
knows how to edit).

Figure 2-7. The Xcode Project Navigator. Click one of the eight icons at the top of the view to switch navigators
CHAPTER 2: Appeasing the Tiki Gods 21

 Symbol Navigator: As its name implies, this navigator focuses on


the symbols defined in the workspace (see Figure 2-8). Symbols are
basically the items that the compiler recognizes, such as classes,
enumerations, structs, and global variables.

Figure 2-8. The Xcode Symbol Navigator. Open the disclosure triangle to explore the classes, methods, and other
symbols defined within each group
22 CHAPTER 2: Appeasing the Tiki Gods

 Find Navigator: You’ll use this navigator to perform searches on all


the files in your workspace (see Figure 2-9). At the top of this pane is a
multileveled pop-up control that lets you select Replace instead of Find,
along with other options for applying search criteria to the text you enter.
Below the text field, other controls let you choose to search in the entire
project or just a portion of it, and specify whether searching should be
case-sensitive.

Figure 2-9. The Xcode Find Navigator. Be sure to check out the pop-up menus hidden under the word Find and under
the buttons that are below the search field
Other documents randomly have
different content
honour. Ben Jonson calls her ‘A tender mother, a discreet wife, a
solemn mistress, a good friend, so lovely and charitable in all her
petite actions, so devote in her whole life,’ etc.
Whatever Sir Kenelm’s real feelings were, his outward grief was
extreme. He retired to Gresham College, lived like a hermit, studied
chemistry, wore a long mourning cloak, and left his beard unshorn.
Although it was generally supposed that his secession from the
Protestant faith took place when he was in Spain, it was not until
1653 that he wrote to his friend Laud (whose admirable answer is
extant) to announce the fact. He was a firm adherent of Charles I.,
and greatly esteemed by Henrietta Maria; but his loyalty got him into
trouble with the Parliament, and he was exiled to France. Returning
in a few months he was imprisoned in 1640 for nearly three years,
and was supposed only to have regained his liberty through the
intercession of the French Queen, who had loved him twenty years
before. His release, however, was conditional. He was forbidden to
take part in any public affairs, and he therefore gave himself up to
literary and scientific pursuits, and engaged in a polemical
correspondence with his quondam tutor, Laud, whom he is said to
have tempted to change his faith, by the bait of a Cardinal’s Hat. Sir
Kenelm returned to France and frequented the Court of his old
flame, the Queen Dowager, where his noble appearance, almost
gigantic size, his handsome features, agreeable conversation and
manners, his learning, and last, but perhaps not least, his
predilection for the occult sciences, made him an universal favourite.
On the death of his eldest son, killed on the Royalist side at the
battle of St. Neot’s, Sir Kenelm returned to compound for his estates,
but was not suffered to remain in England. He went back to Paris,
where Henrietta Maria made him her Chancellor; and he was then
intrusted with a mission to Pope Innocent X., who welcomed him at
first, but after a time the ‘Englishman grew high, and hectored at His
Holiness, and gave him the lie.’
Once more in England, after the dissolution of the Long
Parliament, Cromwell took him into his confidence, hoping by his
mediation to gain over the Roman Catholics.
His conduct in these circumstances has been praised by some and
censured by others, as may well be imagined, according to religious
and political bias. He travelled through France, Lower Germany, and
the Palatinate, always seeking and being sought by men of letters;
and 1660 saw him once more back in his native land.
Charles II. showed him but little favour. He was nominated F.R.S.,
and resided (1663) in a fair house in Covent Garden, where he had a
laboratory. ‘Philosopher, theologian, courtier, soldier; polite, amiable,
handsome, graceful.’ Lord Clarendon’s testimony is, ‘eccentric, vain,
unstable in religion, a duellist.’ These are the counterbalancing
portraits of Sir Kenelm Digby. He desired to be buried near Venetia.
His epitaph was as follows:—
‘Under this tomb the matchless Digby lies,
Digby the great, the brilliant, and the wise;
This age’s wonder, for his noble partes,
Skilled in six tongues, and learn’d in all the artes!
Born on the day he died, th’ eleventh of June,
And that day bravely fought at Scanderoon:
It’s rare that one and the same day should be
The day of birth, and death, and victory.’

He had four sons and one daughter.


No. 40. SIR THOMAS KILLIGREW.
Red slashed doublet. Fair hair. A bracelet on his arm. His hand rests
on a dog’s head.

BORN 1611, DIED 1683.

By Vandyck.

E was the younger son of Sir Robert Killigrew of


Hanworth, County Middlesex, by Mary, daughter of Sir
Henry Wodehouse, who married, secondly, Sir Thomas
Stafford. Thomas, or as he was usually called, Tom
Killigrew, was early initiated into the mysteries of Court
life, being appointed Page of Honour to King Charles the First, to
whom he remained faithful, and followed Charles the Second and his
mother in their exile. About the year 1651 the King sent him in a
diplomatic capacity to Venice, where Killigrew seems to have
disported himself to his heart’s content, and it was evidently here
that he imbibed that passion for music and the drama, which never
forsook him, but which converted him into a dramatist and a
theatrical entrepreneur, rather, we should say, confirmed him in
these tastes which were already developed in his boyhood; for we
have an anecdote of his school days, how he would go to the Red
Bull Tavern, not far from the theatre, during the performance, and
how, more than once, the waiter came in crying, ‘Who will go and be
a devil on the stage, and he shall see the play for nothing?’ an offer
with which young Tom gladly closed. Thus began his career; for was
not he a merry devil the chief part of his life?
Venice, as we have seen, suited his humour well, and Thomas was
evidently one of those foreigners who go on the principle of howling
with the wolves, and doing at Rome more than the Romans do. In
fact, he was so carried away by the vivacity of the Venetians, the
maskings, flirtings, and what not, which he encountered in the fair
city of the sea, that Thomas began to out-Herod Herod, and lived his
life at such a rate as to scandalise the Venetian authorities, who
directed their ambassador at Paris to wait on the English King, and
urge the recall of his envoy. Charles complied, but it was not likely
that the peccadilloes of which ‘Tommaso’ had been guilty should
appear unpardonable in the eyes of the merry monarch, and he
received the delinquent into especial favour, and on the Restoration
Tom became Groom of the Bedchamber, and the King’s inseparable
companion. Pepys, in his diary of 1660, about the time of Charles’s
return to his dominions, records his meeting with Tom, when being
on my Lord Sandwich’s ship, he met, ‘with other fine company, Tom
Killigrew, a merry droll, but a gentleman, full of wit and humour, a
general favourite, especially with the King. And I walked with him for
some time on the deck, and he told most amusing stories.’
Killigrew had not been long in England before he put a darling
scheme into execution, namely, to bring over an Italian troop of
actors from Venice to perform in singing and recitative. He had by
this time set up as a dramatic author, and was instrumental in
introducing into England the fashion of female performers, for, until
the Restoration, actresses had not appeared on the stage, although
in Italy, Spain, and elsewhere, the female characters were always
represented by women. It may easily be believed that this
innovation fell in with the royal taste, and there was great
amusement afforded by a representation of the Parson’s Wedding, a
comedy of Master Killigrew’s own writing, entirely performed by
females. In another portion of his diary Pepys relates how he met
Tom at my Lord Brouncker’s one night in company with a certain
musician, one Signor Baptista, and Killigrew told us how they
proposed to give an opera entirely in the Italian language, and he
goes on to say that Baptista was singer, poet, and all in one, and
that he sang them one of the acts, and that from the words alone,
without any music prickt, which seemed to astonish good Master
Samuel, who makes some of his accustomed sapient remarks on the
occasion: ‘I did not understand the words, and so do not know if
they are fitted, but I perceive there is a proper accent in every
country’s discourse, but I am not as much smitten by it as if I were
acquainted with the language.’
Good Master Pepys had made a discovery in those early times,
which we recommend to the notice of many who pass in these days
for proficients in the vocal line. The newly-born Italian opera now
became the rage, very often, indeed, to the detriment of the English
theatrical companies, so much so that sometimes Killigrew’s own
dramatic productions were played to empty benches. Besides Signor
Baptista there was another eminent musician, Francesco Corbetta,
who not only sang in opera, but gave lessons in singing and the
guitar, an instrument hitherto almost unknown in this country.
‘Famossissimo maestro, di ghitarra,
Qual Orfeo in suonar, ognun il narra!’

Guitar-playing became a perfect mania among the fine ladies and


gentlemen at Court, ‘the King’s relish for that instrument,’ says De
Grammont, ‘helping to bring it into vogue, and the guitar (whether
for show or use) was now as necessary an appendage to a lady’s
toilet-table as her rouge or patch-box. In fact, there was a universal
strumming of the whole guitarrery at Court.’ Lord Arran, a younger
son of the Duke of Ormonde, and his sister were amongst the
greatest proficients; indeed, Lady Chesterfield was as much admired
for her musical talent as for her undoubted beauty, and it was
whispered her lord was very jealous of the Duke of York’s evident
appreciation of both these attractions. Tom Killigrew’s popularity with
the King increased daily, and there was a report that his Majesty
intended to revive the disused office of Court Jester in the person of
his favourite. We believe such an officer had been attached to his
father’s household, but the post could only have been nominal. An
old writer thus describes the duties of a Court Jester, ‘A witty and
jocose person kept by princes, to inform them of their faults, and
those of other people.’ We scarcely give Charles the Second credit
for such a motive in his election. Pepys alludes to the circumstance
in these words, ‘Tom Killigrew has a fee out of the Wardrobe for Cap
and Bells as King’s Jester, and may tease and rule anybody, the
greatest person, without offence, in privilege of his place.’ Of this
privilege Tom took advantage, sometimes in a good cause, for with
all their faults and failings, both he and his kindred spirit, Nell
Gwynne, regretted the bad odour into which Charles had fallen
through his neglect of public affairs, and Nell often admonished her
royal lover on the subject. One day the two friends hatched a small
plot. Says Nelly, ‘I have been just listening to the complaints of one
of the Court Lords, of Charles’s neglect of all duty, and how that he
has quite forgotten the existence of such a thing as a Cabinet
Council, upon which I bet his Lordship £100 that the King should
attend the very next. He sneered, but accepted the wager.’ Now we
do not know if Nelly promised her accomplice to go halves, but we
do know that that evening, when the King was in Madam Gwynne’s
apartments, the door flew open, and in burst Tom, disguised as a
pilgrim. The King swore at him, and asked if he had not heard the
royal command that he should not be disturbed. ‘Oh yes, sire,’ was
the reply, ‘but I was obliged to come and take leave of your Majesty
before my departure.’
‘Why, where the —— are you going, and what does this absurd
masquerading mean?’
‘I am starting this very moment for hell.’
‘Already,’ sneered the King, ‘and on what errand?’
‘To beg and pray of the devil to lend me Oliver Cromwell, if for
ever so short a time, to attend to the affairs of the country, as his
successor spends all his time in pleasure.’
The Jester was forgiven, and Nelly won her wager.
Another time Charles taxed his fool with telling everybody that the
King was suffering from torturing pains in the nose, and asked the
meaning of such a senseless report. ‘I crave your Majesty’s pardon,’
says Tom, ‘I knew you had been led by the nose for so many years,
that I felt sure it must have become tender and painful.’
But the Jester occasionally carried the jest too far; there was a
play called ‘The Silent Woman,’ given in London about this time,
wherein appeared the character of Tom Otter, a henpecked husband,
a reputation which the Duke of York enjoyed at Court. One night
Charles said, ‘I will go no more abroad with Tom Otter and his wife.’
Now the courtiers well knew that when the King made any slighting
allusion to his brother, they were expected to be tickled, so there
was a general roar. The Jester alone looked solemn. ‘I wonder,’ said
he, ‘which is best, to play Tom Otter to your wife or to your
mistress?’—a sally which made Charles very angry, for he felt the
reference was made to Lady Castlemaine, of whom the whole world
knew he stood greatly in awe.
Another evening Tom made a comic onslaught on Lord Rochester,
and that nobleman, actuated perhaps by jalousie de métier, was so
enraged that he dealt the Jester a swinging box on the ear,
unmindful of the royal presence, and threw the whole Court circle
into confusion.
Death alone could put an end to poor Tom’s fooling. He died at his
post at Whitehall in 1682-3, and then ‘where were his gibes, his
gambols, his flashes of merriment, that were wont to set the table in
a roar? Alas! poor Yorick.’
No. 43. MISTRESS HERBERT.
Elizabethan dress. Ruff. Jewelled hat. Auburn hair. Inscription
—‘Richard
Herbert of Blackhall’s wife, being daughter to Newport of Arcole.’

DIED 1627.

By Zucchero.

E cannot do better in giving an account of this most


remarkable and exemplary woman than to quote the
words of her distinguished son, Edward, tenth Lord
Herbert of Cherbury: ‘My mother, Magdalen, was the
fourth daughter of Sir Richard Newport, by his wife,
Margaret, daughter and heir of Sir Thomas Bromley, one of the Privy
Council, and Executor of King Henry the Eighth. She married Richard
Herbert, grandson of Sir Richard Herbert of Blackhall, County
Montgomery, Knight, and surviving her husband, gave rare
testimonies of an incomparable piety to God and love to her
children. She was most assiduous and devout in her daily, both
private and public, prayers, and so careful to provide for her
posterity, that though it were in her power to give her estate, which
was very great, to whom she would, yet she continued long
unmarried, and so provident for them, that after she had bestowed
all her daughters with sufficient portions upon very good
neighbouring families she delivered up her estate and care of her
housekeeping to her eldest son Francis. She had for many years kept
hospitality with that plenty and order as exceeded all, either of her
county or town, for besides abundance of provision and good cheer
for guests, which her son Sir Francis continued, she used ever after
dinner to distribute with her own hands to the poor, who resorted to
her in great numbers. Alms in money she gave also, more or less, as
she thought they needed it. After my mother had lived most
virtuously and lovingly with her husband for many years (who died
in 1597), she after his death erected a fair monument for him in
Montgomery Church, brought up her children carefully, and put them
in good courses for making their fortunes, and briefly was that
woman Dr. Donne has described in his funeral sermon.’
Speaking of his father Lord Herbert says: ‘He was black-haired,
and bearded, of a manly but somewhat stern look, but withal very
handsome; compact in his limbs, and of a great courage.’ His
grandfather was also distinguished for the same quality, and was
noted to be a great enemy to the outlaws and thieves of his time,
who appeared in great numbers in the mountains of
Montgomeryshire. Lord Herbert also commends his grandfather’s
extreme hospitality, which caused it to be an ordinary saying, if any
one saw a fowl rise in the country at that time—‘Fly where thou wilt,
thou wilt light at Blackhall.’
Mistress Herbert had seven sons, of whom the eldest was the
aforementioned Lord Herbert of Cherbury, and three daughters. She
seems to have merited her son’s encomiums. Izaak Walton says of
her: ‘She was a person of superior abilities, and was highly
esteemed for her great and harmless wit, cheerful gaiety, and
obliging behaviour, which gained her a friendship with most of any
eminent birth or learning in the University of Oxford, where she
resided four years during the time of her widowhood, in order to
superintend the education of her children, who were all young at the
time of their father’s death. When she had provided for them she
took to her second husband, Sir John Danvers, Knight, brother and
heir to Henry, Earl of Danby, who highly valued both her person and
most excellent endowments of mind. It was Magdalen Newport, Mrs.
Herbert, and Dame Danvers, who inspired those favourite lines of Dr.
Donne, Dean of St. Paul’s, so often quoted—
‘No spring or summer beauty hath such grace
As I have seen in an autumnal face.’
She lies buried at Chelsea.
No. 44. THOMAS CROMWELL, EARL OF ESSEX.
Black and white dress.

By Holbein.

E was the son of a blacksmith at Putney; his mother, who


married again, sent him to a small school, where he
learned little more than reading, writing, and the
rudiments of Latin. When quite young he evinced a
passion for travel, and set out for the Continent with
very scanty means, which were soon exhausted, and he found
himself at Antwerp without money or connections of any kind. But
he was energetic and hard-working, and he soon found employment
as a clerk in an English factory established in the city. Glad as
Cromwell was to earn his livelihood, the drudgery and confinement
of the life were irksome to the eager restless spirit of our young
adventurer, and he took advantage of the first opportunity to escape.
He made acquaintance with some countrymen from Boston in
Lincolnshire, bound for Rome, in order to obtain certain indulgences
from the reigning Pope, Julius the Second. These men soon became
aware that Cromwell’s intelligence and capability were likely to make
him a valuable fellow-traveller. They therefore proposed to convey
him to Italy, an offer with which it may be imagined Cromwell
eagerly closed. At Rome he rose into favour at the Vatican by his
talent and ability, added to which substantial qualifications our young
traveller made himself acceptable to the Pope by ministering to the
well-known tastes of Julius for good living. He is said to have
instructed the Papal cook in the art of preparing many a delicacy for
the Pontiff’s table, till then unknown in Rome, especially ‘some rare
English jellies, which his Holiness pronounced delicious.’ Italy was at
that period the theatre of constant warfare, and Cromwell became
not only a spectator, but an actor in many of the exciting events,
serving for a time as trooper in the army of the Duke, afterwards
Connétable, de Bourbon.
This great commander had left the service of France in disgust,
and had espoused the cause of Charles the Fifth, Emperor of
Germany. A companion in arms was John Russell, eventually Earl of
Bedford; a man who shone alike as a soldier and a diplomatist, and
had been employed in the latter capacity by Henry the Eighth, and
his prime minister, Cardinal Wolsey. Being at Bologna a plot was
formed to seize his person and send him prisoner to Paris, the hotel
in which he lodged being already guarded by the soldiers of the
Gonfaloniere. Thomas Cromwell was also in Bologna at that time,
and no sooner did he receive intelligence of the affair than he went
to the municipal authorities representing himself as a Neapolitan
acquaintance of the English knight, and offering to persuade him to
give himself up quietly. He thus gained access to Russell’s presence,
and providing him with the disguise of a peasant contrived in the
most skilful manner to effect his escape. Russell urged his deliverer
to accompany him, but Cromwell was not disposed to leave Italy so
soon, and entered the service of a rich merchant at Venice.
Cromwell was said to have been present at the battle of Pavia,
where Francis the First of France was taken prisoner. On his return
to England, the man whose life and liberty he had saved, came
forward to lend him a helping hand.
Russell, then in much repute at Court, recommended him to the
patronage of Wolsey, then in the zenith of his power. The Cardinal
took Cromwell into his service and confidence, and made him
secretary and chief agent in the great scheme of the dissolution of
the religious houses, which was now carrying on, the funds thus
raised being ostensibly apportioned to defraying the expenses
attendant on the erection of the colleges which Wolsey was now
founding—
‘Those twin seats of learning,
Ipswich and Oxford.’
But there were whisperings abroad that much of the money thus
obtained overflowed into the pockets of ‘master and man,’ a
circumstance which Cromwell emphatically denied in a conversation
with Master George Cavendish, one of the Cardinal’s gentlemen, and
his eventual biographer. The question of Cromwell’s fidelity to his
master, when Wolsey fell on evil days, has been differently treated
by different writers; but there is no doubt that when Wolsey left
London in disgrace, Cromwell followed him to Esher—or Asher, as it
is written by Master Cavendish—who tells us he went into the great
chamber, and to his surprise found Master Cromwell standing in the
large window, the tears distilling from his eyes, with a primer in his
hand, praying earnestly,—‘the which was a strange sight,’ for it did
not appear that the said Master Cromwell was by any means given
to devotion. Cavendish inquired into the cause of his sorrow, asking
anxiously if he considered their master’s case to be so very hopeless,
on which Cromwell, with much candour, confessed that it was his
own fate he was bewailing, for it seemed most likely that he was on
the point of losing everything for which he had been travailing all the
days of his life; moreover, that he was in disdain of all men simply
for doing his master’s service, through which he had never increased
his living, on the contrary, had been a heavy loser. Then he confided
to Master Cavendish how, that very afternoon, when the Cardinal
had dined, it was his (Cromwell’s) intention to ride with all speed to
London, and so to Court, ‘where I will either make or mar ere I
come back again.’ Assuredly in the audience which he solicited and
obtained did Master Cromwell make, and not mar, as far as he
himself was concerned. He had a long and explicit conversation with
the King, into whose favour he ingratiated himself by suggesting the
very line of conduct on which he well knew Henry’s heart was bent.
Acquainted with the Monarch’s infatuation for Anne Boleyn, he now
suggested, as if from his own notion of advisability, that the King
should throw off all allegiance to the Pope, declare himself supreme
head of the Church throughout his own kingdom, and thus facilitate
the much desired measure of his divorce from Queen Katherine.
Such palatable advice was indeed well calculated to win Henry’s
good graces, and from that moment Cromwell’s rapid rise began.
The King, knowing what a valuable auxiliary he had proved to his
late patron in the matter of the suppression of the religious houses,
resolved to secure Cromwell’s services for the same purpose. He
therefore confirmed him in the office of Steward of the Dissolved
Monasteries, made him a Privy Councillor, a Knight, Secretary of
State, Master of the Royal Jewel-house, Clerk of the Hanaper (a
lucrative post in the Court of Chancery), and what Cromwell’s
enemies termed ‘the Lord knows what.’ In 1535 Visitor-General of
the said suppressed monasteries throughout the realm, in which
capacity Sir Thomas incurred much censure, and was branded by
many as cruel, rapacious, and overbearing. In our judgment of this
sentence we must take into consideration the fever heat at which
religious animosity now stood; suffice it to say that Cromwell
satisfied the views of his royal master, and was not Henry cruel,
rapacious, and overbearing? Fabulous sums were extorted from the
exchequers of these establishments, and it was almost universally
believed that the favourite came in for a considerable share of the
booty. It was indeed evident he did not remember the injunction laid
upon him by Sir Thomas More, namely, that he should advise the
King what he ought to do, not only what he was able to do. In 1536
he was made Privy Seal, and the same year Baron Cromwell of
Okeham, County Rutland, and (the authority of the Pope being by
this time abolished in England) Henry instituted a new office, to
which he appointed his favourite. This was Vicar-General, or in other
words, Supreme Head of the Church, as representative of the King,
in which capacity he sat in the House of Lords, and also at
Convocation above the Archbishop of Canterbury. The office included
that of Principal Commissary for the Administration of Justice in all
ecclesiastical affairs; of the godly reformation, and the redress of all
errors, heresies, and abuses of the English Reformed Church, both in
Parliament and Convocation.
It was indeed strange that the man who, a very short time before,
had professed infidel doctrines (and was so unsettled in his creed
that when Cavendish found him at prayers, the primer in his hand
should be our lady’s matins) strange to say that this individual
should now come forward as the principal pillar of the Reformation.
Dr. Hook, in his Lives of the Archbishops of Canterbury, says,
Cromwell ‘was not a real Protestant, and was generally supposed to
be a man who supported the party from which he could obtain most,
a statesman whose religion depended on politics, and who had no
knowledge of theological subjects.’ Yet from the circumstances in
which he was now placed all the English Protestants rallied round
him, and those of Germany treated with him. In his new capacity
Cromwell issued the most stringent and binding regulations for the
conduct of the reformed clergy, was indefatigable in propagating the
Bible throughout the country, causing it to be read in churches, and
placed in convenient parts of the building, where the parishioners
themselves could refer to it on their own account. But Cromwell’s life
forms part of the history of the reign of Henry the Eighth, and
indeed of the Reformation itself. And it is incumbent on us to
condense this narrative lest it exceed the prescribed bounds.
He continued to receive marks of favour from the King, but his
keen eye detected the gathering clouds in his own future; and he
knew if Henry once failed him there would be little hope of
stemming the tide of unpopularity which threatened to overpower
him. He well knew that he was hated by all classes; the nobility, who
grudged all the titles and honours bestowed on ‘the blacksmith’s
son’; the Roman Catholics, who had good reason to detest him;
while the reformed clergy rebelled against many of the changes and
innovations which the Vicar-General had instituted in the services
and conduct of the Church; and the poorer classes were indignant
with him for depriving them of the bounty which they had so long
received from the religious houses. Cromwell had good cause to be
uneasy. He began by propitiating ‘the poor and needy,’ who now
flocked by invitation to the gate of his house in Throckmorton Street,
oftentimes twice a day, where they were regaled with bread and
meat and money. He then set on foot negotiations with the
Protestant Princes of Germany, more especially the reigning Duke of
Cleves, in order to bring about a marriage between that Prince’s
sister and Henry the Eighth, who was at this moment in one of his
transitory intervals of widowhood. Lord Cromwell imagined that a
Protestant queen of his own selection would be an invaluable ally at
Court, and help him to retain the favour of the King, who was
persuaded into the belief that the Lady Anne of Cleves was not only
‘fair and portly,’ but comely in face and feature, an error in which
Henry was confirmed by a very flattering portrait from the pencil of
Holbein. So the Princess was sent for to come over to England, and
a magnificent cortége was despatched, with the Archbishop of
Canterbury himself, to bring her on her way to London; and Henry
conceived the romantic idea of riding down to Rochester in disguise
to waylay his bride. Alas! for the eager glance which his Grace cast
into the travelling coach, where sat a lady tall and portly indeed, but
coarse and ugly in face and feature! Henry, we are told, was
‘alarmed and abashed,’ but he also was furious. He felt he had been
deceived, and he sent for Cromwell and bade him devise some
means for the prevention of the marriage. It was too late; matters
had gone too far, and the ceremony was performed.
It would appear that at the time the King did not realise the idea
that Cromwell was the principal instigator of the hated union, for it
was after the marriage that he was raised to the Earldom of Essex,
and made Lord Chamberlain, and his son granted a separate
peerage. We know from the pages of history how the King’s horror
of ‘the Flanders mare’ increased day by day, and he never rested till
he had obtained a divorce, soon followed by the downfall of the
newly created Earl of Essex, whose ruin was resolved on.
The Duke of Norfolk was intrusted with the task of arresting his
enemy at the Council Board on the opening of Parliament in June
1540, and despatching him to the Tower, nor was he loth to carry
out the royal command. Essex claimed a trial by his Peers, but the
privilege was denied him. He was condemned, says Dr. Hook, by the
iniquitous statute, admitting of attainder without trial, a measure of
which he was not the actual founder, as affirmed by some writers,
but the reviver of the same, and therefore by many pronounced
deserving of his fate.
He was accused of high treason, heresy, embezzlement, and a
host of other misdemeanours, but there is little doubt the worst
offence in Henry’s eyes was his instrumentality in promoting the
hateful marriage with Anne of Cleves.
The only voice that was raised in his behalf was that of Archbishop
Cranmer, who wrote a most eloquent letter to the King, entreating
him to spare the life of Lord Essex, but it was unavailing. Cromwell’s
demeanour in the Tower was very different from that which had
characterised Sir Thomas More. He addressed the most abject letters
to Henry, and would have accepted life at almost any price. He wrote
‘with a heavy heart and trembling hand,’ and signed himself, ‘Your
highness’s most humble and wretched prisoner and poor slave,
Thomas Cromwell.’ While underneath the subscription came the
words, ‘I cry for mercy, mercy, mercy!’
Henry caused the letters to be read to him four times, and at one
moment showed signs of relenting, but in the end was (as usual)
inexorable. Four days from the passing of the sentence, Lord Essex
was led forth to execution, and beheaded on Tower Hill. He made a
speech full of loyalty and submission to the royal will, words which
were thought to have been dictated by paternal solicitude for the
welfare of his only son. He furthermore confessed his sins, repenting
that he had ever abandoned the Catholic faith to which he now
returned, for in that he was resolved to die; then kneeling in prayer,
‘he submitted his neck to the executioner, who mangled him in a
shocking manner.’
No. 46. LADY KILLIGREW.
Standing. White satin gown, dark drapery. Hands crossed.
Brown curls.

By Vandyck.

M
istress Cecilia Crofts, maid of honour to the Queen Henrietta
Maria?
PRINCIPAL STAIRCASE.
PRINCIPAL STAIRCASE.
No. 1. GRACE, COUNTESS OF DYSART.
Pale yellow dress. Leaning her elbow on a table.

DIED 1744.

By Wright.

HE was the daughter of Sir Thomas Wilbraham of


Woodhey, County Chester, by Elizabeth, daughter and
sole heir of Edward Mytton, Esq., of Weston-under-
Lizard, County Stafford. She married, 1680, Lionel
Tollemache, Earl of Dysart, and, becoming co-heir with
her sister, the Countess of Bradford, took large estates to her
husband’s family. Lady Dysart had one son, who died v.p., and two
daughters.
No. 2. MARY, WIFE OF RICHARD NEWPORT, SECOND
EARL OF BRADFORD.
Pale yellow dress. Pink drapery. Holding a flower.

BORN 1661, DIED 1737.

By Wright.

HE was the daughter and co-heir of Sir Thomas


Wilbraham of Woodhey, County Chester, Bart., by
Elizabeth, daughter and co-heir of Edward Mytton, Esq.
of Weston-under-Lizard, which estate (besides a large
fortune from her father) Lady Bradford inherited from
her mother, and brought into the Newport family.
It is seldom the lot of any woman to live continuously in one loved
home, but Mary Wilbraham was born, married, died, and was buried
at Weston, where her childhood, youth, the chief part of her married
life, and the latter days of her widowhood were all passed, and
which she brought into the Newport family. Francis, Earl of Bradford,
and his wife were most anxious to secure for their eldest son so
desirable a match as this young lady presented, not only on account
of her noble inheritance, but in respect of her amiable qualities and
the comeliness of her person.
They accordingly made good settlements on Lord Newport to
facilitate the union. We have a list of the lands and messuages
allotted to him, but to prove their worth we consider two of them
will suffice, at least in point of syllables, namely—the Manors of
Ginnioneth-ys-Kerdine, and Dykewyde, in the county of Cardigan.
Lady Bradford had six sons, of whom four died without children, and
two, Henry and Thomas, succeeded to the Earldom, and four
daughters, Mary, who died unmarried; Elizabeth, wife of James
Cocks of Worcester, Esq., ancestor to the present Lord Somers;
Anne, married to Sir Orlando Bridgeman of Castle Bromwich, County
Warwick, Bart.; and Diana, married to Algernon Coote, Earl of
Mountrath. Mary, Countess of Bradford, survived her husband many
years, and lies buried by his side at Weston. Her loss was deeply
mourned by all classes, especially by the poor, to whom her charity
was unbounded.
No. 3. RICHARD NEWPORT, SECOND EARL OF
BRADFORD.
Slashed dress of golden brown. White sleeves. Wig.

BORN 1644, DIED 1723.

By Sir Peter Lely.

E was the eldest son of the first Earl of Bradford, by Lady


Diana Russell. During his father’s lifetime he represented
Shropshire in Parliament for many years, and gained
great popularity in his county by his strenuous support
of the Bill of Exclusion, which obtained for him a
complimentary address signed by every member of the grand jury,
consisting of all the principal landholders of the neighbourhood. He
was Privy Councillor in the reigns of Queen Anne and George the
First, and Lord Lieutenant and Custos Rotulorum for the county of
Montgomery. In 1681 he married the daughter and co-heir of Sir
Thomas Wilbraham of Woodhey, and Weston-under-Lizard, Bart., by
whom he had a numerous family. During his father’s lifetime he
resided chiefly at Eyton-upon-Severn, but in later days he took up
his abode at Weston, his wife’s inheritance in Staffordshire.
No. 4. SIR ORLANDO BRIDGEMAN.
Robes of the Lord-Keeper. Holding the purse. Oval, in a square
frame.

BORN 1609, DIED 1674.

By Riley.

HE son of Dr. John Bridgeman, Bishop of Chester, by


Elizabeth, daughter of Dr. Helyar, Canon of Exeter, and
Archdeacon of Barnstaple. Educated by his father until
he went to Queens’ College, Cambridge, where he took
his degree of B.A. in 1623. The following year he
entered the Inner Temple, and applied himself vigorously to the
study of common law, ‘of which he became,’ says Lord Campbell, ‘a
profound master, caring little in comparison for either literature or
politics.’ When called to the bar he made himself remarkable for his
diligent attention to business, although he had the expectation of a
goodly inheritance from his father. At the commencement of the
Long Parliament Orlando Bridgeman was returned for the borough of
Wigan in Lancashire. He voted silently, but, with the exception of
some measures on which he had conscientious scruples, almost
invariably for the King. He was also one of the few who voted
against the attainder of Lord Strafford, in whose behalf he made a
short but manly appeal. When the civil war broke out Orlando did
not indeed, as was the case with several lawyers, throw aside the
gown for the sword; but he went into the north, and in the city of
Chester, and elsewhere, did the King good service by affording the
royal troops all the assistance in his power, in cooperation with his
father, the Bishop of the diocese. Clarendon tells us how ‘the city of
Chester remained true to his Majesty, influenced thereto by the
credit and example of Bishop John Bridgeman, and the reputation
and dexterity of his son Orlando, a lawyer of very good estimation.’
For these proofs of loyalty Bridgeman was expelled the House of
Commons, and the Bishop’s estates sequestrated. But when Charles
summoned the members of both Houses that had been faithful to
him, to his own Parliament at Oxford, Orlando Bridgeman took his
seat as member for Wigan, in Christchurch Hall, and was there
nominated by patent (sealed by Lord-Keeper Lyttleton) to the post of
Attorney-General of the Court of Wards and Liveries, ‘an office,’ says
Lord Campbell, ‘when actually exercised, of great importance and
emolument, but now a mere feather in his cap, which Parliament
would not allow him to wear in their sight. At the time of the Treaty
of Uxbridge, Bridgeman was chosen one of the Commissioners, and
was thereto designated by his new title, but the potentates of
Westminster would not acknowledge the appointment as valid, and
treated him as plain Orlando Bridgeman.’ When Oxford capitulated to
Fairfax, he retired to his country house at Morton, where he was
joined by the Bishop, and afterwards he proceeded privately to
London.
During the interregnum he refused to put on his gown or to plead,
but contented himself with acting as a conveyancer or chamber
counsel. Yet we are informed that he took great note of passing
events, whether judicial or political, and though he prudently
abstained from any small plot hatching in the King’s name, which he
considered would be prejudicial to the royal cause, yet to the great
measures which affected the Restoration our lawyer gave his strong
adherence, and rejoiced in the return of Charles the Second to
England. He had quick promotion, being made Serjeant-at-Law, Lord
Chief Baron of the Exchequer, and Speaker of the House of Lords in
the absence of the Lord Chancellor. His conduct on the trial of the
regicides has naturally been differently judged, according to the bias
of party feeling, but at all events his eloquence in charging the jury
was highly extolled at the time, and when he had concluded the
applause was so great that Judge Bridgeman felt himself called upon
to check the expression thereof, saying, ‘that it was more suitable for
the audience of a stage-play rather than a court of justice.’ His
language indeed was rather fantastic and flowery, but that was the
fashion at the time. He explained that ‘the treason of the prisoners
consisted not only in compassing and imagining the King’s death,
but in executing him in front of his own palace; in fact, not only
laying the cockatrice’s egg, but brooding upon the same, until it had
brought forth a serpent!’ On the expiration of the trials, Bridgeman
was made a Baronet and Chief-Justice of the Common Pleas; and it
was said of him that while presiding in this Court his reputation was
at its zenith, and ‘his moderation and equity were such that he
seemed to carry a chancery in his breast.’ In the intrigues which
were being carried on against Lord Clarendon, Sir Orlando took no
part; indeed his conduct was invariably marked by generosity
towards the man whom he was destined to supplant, and he did all
in his power to prevent the Chancellor’s impeachment. In 1667 he
was appointed Lord-Keeper at the instigation of some of the King’s
advisers, male and female, and it was whispered among his enemies
that in that capacity he was at first more complaisant than his
predecessor in affixing the great seal to royal grants, in favour of
such personages as Lady Castlemaine, and others of her calibre. Be
this as it may, the atrocious proceedings of the Cabal roused the
Lord-Keeper into resistance, and the opposition he offered to these
unscrupulous men hastened his downfall. His own family were also
most prejudicial to his prosperity, his wife being an ‘intriguer and
intermeddler,’ combining with his sons in matters with which they
had no concern. Bridgeman was losing favour at Court; he had lately
made himself obnoxious to the King and his surroundings by
opposing many of their measures, and when he refused to confirm
the Act of Toleration on the ground of illegality, Lord Shaftesbury
hastened to Charles’s presence bent on mischief, for that nobleman
had long had his eyes greedily directed towards the Great Seal, and
he became very eloquent in counting up all Sir Orlando’s
misdemeanours, ending by his disinterested advice for that
minister’s instant dismissal. Charles took a little time to be
persuaded, but after a while he sent off secretary Coventry to
demand the bone of contention from the Lord-Keeper. Bridgeman
was all unprepared for the hasty and peremptory message, but he
had no option, and the Great Seal was delivered to the royal
messenger. Charles kept it in his own custody all night, and the next
morning consigned it with the title of Lord Chancellor into the willing
hands of Anthony Ashley Cooper. After his dismissal from office Sir
Orlando retired to his villa near Teddington, where he died, and was
buried. He was twice married—first to Judith, daughter and heir of
John Kynaston, Esq. of Morton, County Salop, who died at Oxford,
during the usurpation, and was there buried. He had an only son, Sir
John Bridgeman, his successor. Sir Orlando had for his second wife,
Dorothy, daughter of Dr. Saunders, Provost of Oriel College, Oxford,
and relict of George Cradock, Esq. of Carsewell Castle, County
Stafford, by whom he had two sons and one daughter, namely, Sir
Orlando, created a Baronet; Sir Francis, knighted in 1673, who
married Susanna, daughter and heir of Sir Richard Barker, Knight,
but had no children; and Charlotte, married to Sir Thomas
Myddleton of Chirk Castle.
As must invariably be the case with men in prominent positions,
more especially in times of great civil, religious, and political
struggles, Sir Orlando Bridgeman’s character was by turns eulogised
and blamed; in spite of his loyal services to Charles the First, that
King found occasion to censure his faithful servant at the time of the
Treaty of Uxbridge, on a question of religion, ‘having,’ said his
Majesty, ‘expected otherwise from the son of a Bishop.’ Yet Sir
Orlando was a staunch Churchman. Burnet’s testimony was merely
to his judicial capacity. He said: ‘Bridgeman’s practice was so entirely
in common law that he did not seem to understand what equity
was.’ Roger North said: ‘He was a celebrated lawyer, and sat with
high esteem in the place of Chief-Justice of Common Pleas: the
moving him then to the Chancery did not contribute to his fame’;
while elsewhere we are told ‘he carried a chancery in his breast.’ ‘He
grew timorous, which was not mended by age; he laboured to
please everybody, and that is a temper of ill consequence in a judge.’
On the other hand, Lord Nottingham writes: ‘It is due to the memory
of so great a man to mention him with reverence and veneration for
his learning and integrity.’ While Lord Ellenborough extols him as an
eminent judge, distinguished by the profundity of his learning and
the extent of his industry. At all events, there is no doubt that the
name of Sir Orlando Bridgeman, Lord-Keeper of the Great Seal,
continues to be honoured, not only in the annals of his own family,
but in the learned profession of the Law.
No. 5. JOHN BRIDGEMAN, BISHOP OF CHESTER,
FATHER OF THE LORD-KEEPER.
Black gown and ruff. Shield episcopal. Arms of Chester, impaling
Bridgeman. Dated 1616. Aged 41.

BORN 1575, DIED 1657-8.

By Jansen.

DWARD BRIDGEMAN was the younger son of William


Bridgeman of Dean Parva, in the county of Gloucester.
He settled in the city of Exeter, and was, in 1578, High-
Sheriff of the said city and the county of Devon. His son
John was born in Exeter, in a house not far from the
palace-gate, which seemed an omen of his future dignity. He was a
studious boy, and loved his books, and was carefully kept at school
until it was deemed advisable ‘to transplant him to the University,’
when he was entered at Magdalen College, Cambridge, of which he
became a Fellow, and eventually the Master. In 1600, being M.A., he
was admitted ad eundem at Oxford, and here he attained the degree
of Doctor of Divinity, being the highest, we are told, ‘a scholar can
receive, or the University bestow.’ Dr. Bridgeman’s character for
learning and piety, combined with refinement of manners and good
breeding, had reached the ears of King James the First, who
appointed him one of his Domestic Chaplains, and soon afterwards
he became incumbent of Wigan in Lancashire. For upwards of two
hundred years, even to the present day, the living in question has
been held, with scarcely any intermission, by a member of the family
of Bridgeman. In 1619 the Doctor was raised to the See of Chester,
being consecrated at Lambeth, at the same time as the Bishops of
Oxford and Bristol. Now the King taking into consideration that the
Bishopric of Chester was less lucrative than some others, His Majesty
also preferred John Bridgeman to the living of Bangor in Wales,
which he was to hold ad commendam, or temporarily. Collins tells us
that his Lordship was not present in the Upper House, in the year
1641, when the bishops protested against the proceedings in
Parliament, and were impeached, and sent to the Tower, whereby he
was saved the tedious imprisonment to which his right reverend
brethren were subjected. But all his proclivities were Royalist, and
during the usurpation, his estates being sequestrated, he took
refuge at his son’s country house at Moreton, near Oswestry, in
Salop, where he died about the year 1657 or 1658, being buried in
the neighbouring church of Kinnerley, and not in the Cathedral of
Chester, as some writers have it.
This worthy Prelate was said to have been ‘as ingenious as he was
brave, and a great patron of those gifts in others which he himself
owned. He, moreover, was the father of that great and good man,
Sir Orlando Bridgeman, the Lord-Keeper, who was a glory to his
family, and indeed to the country at large.’ The Bishop of Chester
married Elizabeth, daughter of Dr. Helyar (of a good old
Somersetshire family), Canon of Exeter, and Archdeacon of
Barnstaple, by whom he had five sons—
1. Sir Orlando Bridgeman, afterwards First Baronet, and eventually
Lord-Keeper.
2. Dove, Prebendary of Chester, married Miss Bennet of Cheshire
(who survived him), by whom he had one son, Charles, Archdeacon
of Richmond, in Yorkshire, who died unmarried 1678. The widow of
Dove Bridgeman married, as her second husband, Dr. John Halkett,
Bishop of Lichfield.
3. Henry Bridgeman, who was indeed rich in church preferment,
being successively Rector of Bangor and Barrow, and Bishop of the
Isle of Man. He married Catherine, daughter of Robert Lever, of
Lancashire, Gent., by whom he had one daughter, who married Sir
Thomas Greenhalgh of Brundlesham, County Lancaster.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like