Preface

Aut lego vel scribo; doceo scrutorve sophian.

Sedulius Scottus

On June 2, 2014, Apple’s WWDC keynote address ended with a shocking announcement: “We have a new programming language.” This came as a huge surprise to the developer community, which was accustomed to Objective-C, warts and all, and doubted that Apple could ever possibly relieve them from the weight of its venerable legacy. The developer community, it appeared, had been wrong.

Having picked themselves up off the floor, developers immediately began to examine this new language — Swift — studying it, critiquing it, and deciding whether to use it. My own first move was to translate all my existing iOS apps into Swift; this was enough to convince me that, for all its faults, Swift deserved to be adopted by new students of iOS programming, and that my books, therefore, should henceforth assume that readers are using Swift.

Therefore, Swift is the programming language used throughout this book. Nevertheless, the reader will also need some awareness of Objective-C (including C). The Foundation and Cocoa APIs, the built-in commands with which your code must interact in order to make anything happen on an iOS device, are still written in C and Objective-C. In order to interact with them, you have to know what those languages would expect. For example, in order to pass a Swift array where an Objective-C NSArray is expected, you need to know what consitutes an object acceptable as an element of an Objective-C NSArray.

If you don’t already know the Swift language and how it interacts with Objective-C, you’ll want to start with my other book, iOS 9 Programming Fundamentals with Swift. It is both an introduction and a companion to Programming iOS 9. Like Homer’s Iliad, Programming iOS 9 begins in the middle of the story, with the reader jumping with all four feet into views and view controllers, and with a knowledge of the language and the Xcode IDE already presupposed. Discussion of the programming language, as well as the Xcode IDE (including the nature of nibs, outlets, and actions, and the mechanics of nib loading), plus the fundamental conventions, classes, and architectures of the Cocoa Touch framework (including delegation, the responder chain, key–value coding, memory management, and so on) — material that constituted Chapters 1–13 in the early editions of this book, but whose presence was eventually deemed to be making the book unwieldy in size and scope — has now been relegated to iOS 9 Programming Fundamentals with Swift.

So if something appears to be missing from this book, that’s why! If you start reading Programming iOS 9 and wonder about such unexplained matters as Swift language basics, the UIApplicationMain function, the nib-loading mechanism, Cocoa patterns of delegation and notification, and retain cycles, wonder no longer — I don’t explain them here because I have already explained them in iOS 9 Programming Fundamentals with Swift. If you’re not sufficiently conversant with those topics, I’d suggest that you might want to read that book first; you will then be completely ready for this one.

The Scope of This Book

To a large extent, iOS 9 represents a pause in the steady march of revisions, often quite radical, that Apple has felt free to introduce with every major system update since iOS 3. In my opinion, this is all to the good. iOS 9, for the most part, is not terribly different from iOS 8. Instead, it consists mostly of fairly small but valuable rationalizations of iOS 8, giving the system’s growth and development a chance to catch up with itself. For example:

  • iOS 9 introduces a new notation for describing a layout constraint.
  • iOS 9 expands the power of UIKit dynamics.
  • iOS 9 implements unwind segues in such a way that they actually work.

In addition, many small bugs are fixed; these fixes do nothing for those who want their apps to run under iOS 8, but they are welcome nonetheless. To cite just one instance, UIProgressView custom progress images, which stopped working in iOS 7, are working once again in iOS 9.

iOS 9 also brings some important linguistic improvements. A major issue that had to be worked around in the previous edition of this book, covering iOS 8 and Swift 1.2, was that not every C and Objective-C API could be called from Swift, necessitating the frequent use of Objective-C “helper” methods. But in iOS 9 and Swift 2.0, this is no longer the case; I’m happy to say that no Objective-C code appears in this edition.

iOS 9 does introduce a few grand sweeping innovations, such as App Transport Security and iPad multitasking; I am less happy with these, but of course I do document them nonetheless.

Here’s a summary of this book’s major sections:

  • Part I describes views, the fundamental units of an iOS app’s interface. Views are what the user can see and touch in an iOS app. To make something appear before the user’s eyes, you need a view. To let the user interact with your app, you need a view. This part of the book explains how views are created, arranged, drawn, layered, animated, and touched.
  • Part II starts by discussing view controllers. Perhaps the most remarkable and important feature of iOS programming, view controllers enable views to come and go coherently within the interface, thus allowing a single-windowed app running on what may be a tiny screen to contain multiple screens of material. This part of the book talks about all the ways in which view controllers can be manipulated in order to make their views appear. It also describes every kind of view provided by the Cocoa framework — the built-in building blocks with which you’ll construct an app’s interface.
  • Part III surveys the most important secondary frameworks provided by iOS. These are clumps of code, sometimes with built-in interface, that are not part of your app by default, but are there for the asking if you need them, allowing you to work with such things as sound, video, user libraries, mail, maps, and the device’s sensors.
  • Part IV wraps up the book with some miscellaneous but important topics: files, networking, threading, and how to implement undo.
  • Appendix A summarizes the most important lifetime event messages sent to your app delegate.
  • Appendix B catalogs some useful Swift utility functions. You should keep an eye on this appendix, consulting it whenever a mysterious method name appears. For instance, my example code frequently uses my delay function, which embraces dispatch_after with a convenient shorthand; when I use delay and you don’t know what it is, consult this appendix.

Someone who has read this book (and who, it goes without saying, is conversant with the material in iOS 9 Programming Fundamentals with Swift) will, I believe, be capable of writing a real-life iOS app, with a clear understanding of what he or she is doing and where the app is going as it grows and develops. The book itself doesn’t show how to write any particularly interesting iOS apps; but it is backed by dozens of example projects that you can download from my GitHub site, http://github.com/mattneub/Programming-iOS-Book-Examples, and it constantly uses my own real apps and real programming situations to illustrate and motivate its explanations.

Just as important, this book is intended to prepare you for your own further explorations. In the case of some topics, especially in Parts III and IV, I guide you past the initial barrier of no knowledge to reach an understanding of the topic, its concepts, its capabilities, and its documentation, along with some code examples; but the topic itself may be so huge that there is room only to introduce it here. Your feet, nevertheless, will now be set firmly on the path, and you will know enough that you can now proceed further down that path on your own whenever the need or interest arises.

Indeed, there is always more to learn about iOS. iOS is vast! It is all too easy to find areas of iOS that have had to be ruled outside the scope of this book. In Part IV, for example, I peek at Core Data, and demonstrate its use in code, but a true study of Core Data would require an entire book of its own (and such books exist); so, having opened the door, I quickly close it again, lest this book suddenly double in size. By the same token, many areas of iOS are not treated at all in this book:

OpenGL
An open source C library for drawing, including 3D drawing, that takes full advantage of graphics hardware. This is often the most efficient way to draw, especially when animation is involved. iOS incorporates a simplified version of OpenGL called OpenGL ES. See Apple’s OpenGL Programming Guide for iOS. Open GL interface configuration, texture loading, shading, and calculation are simplified by the GLKit framework; see the GLKit Framework Reference. The Metal and (new in iOS 9) Metal Kit and Model I/O classes allow you to increase efficiency and performance.
Sprite Kit
Sprite Kit provides a built-in framework for designing 2D animated games.
Scene Kit
Ported from OS X, this framework makes it much easier to create 3D games and interactive graphics.
Gameplay Kit
New in iOS 9, this framework provides architectural underpinnings for writing a game app.
Accelerate
Certain computation-intensive processes will benefit from the vector-based Accelerate framework. See the vDSP Programming Guide.
Game Kit
The Game Kit framework covers three areas that can enhance your user’s game experience: Wireless or Bluetooth communication directly between devices (peer-to-peer); voice communication across an existing network connection; and Game Center, which facilitates these and many other aspects of interplayer communication, such as posting and viewing high scores and setting up competitions. See the Game Kit Programming Guide. New in iOS 9, users can even make screencasts of their own game play for sharing with one another; see the ReplayKit Framework Reference.
Advertising
The iAD framework lets your free app attempt to make money by displaying advertisements provided by Apple. See the iAD Programming Guide.
Newsstand
Your app may represent a subscription to something like a newspaper or magazine. See the Newsstand Kit Framework Reference.
Printing
See the “Printing” chapter of the Drawing and Printing Guide for iOS.
Security
This book does not discuss security topics such as keychains, certificates, and encryption. See the Security Overview and the Security framework.
Accessibility
VoiceOver assists visually impaired users by describing the interface aloud. To participate, views must be configured to describe themselves usefully. Built-in views already do this to a large extent, and you can extend this functionality. See the Accessibility Programming Guide for iOS.
Telephone
The Core Telephony framework lets your app get information about a particular cellular carrier and call.
Pass Kit
The Pass Kit framework allows creation of downloadable passes to go into the user’s Passbook app. See the Passbook Programming Guide.
Health Kit
The Health Kit framework lets your app obtain, store, share, and present data and statistics related to body activity and exercise. See the HealthKit Framework Reference.
External accessories
The user can attach an external accessory to the device, either directly via USB or wirelessly via Bluetooth. Your app can communicate with such an accessory. See External Accessory Programming Topics. The Home Kit framework lets the user communicate with devices in the physical world, such as light switches and door locks. See the HomeKit Framework Reference.
Handoff
Handoff permits your app to post to the user’s iCloud account a record of what the user is doing, so that the user can switch to another copy of your app on another device and resume doing the same thing. See the Handoff Programming Guide.
Spotlight
New in iOS 9, the user’s Spotlight search results can include data supplied by your app. See the Core Spotlight Framework Reference.

Some Swift Conventions

I have had to settle on some conventions for presenting and describing code. The most important question has been how to state the name of a method. My solution, if this method is defined originally through an Objective-C API (that is, through Cocoa), is to give the method’s Objective-C name. As an example, what is the name of the method that you call when you set a value using key–value coding? The actual call, in Swift, would be something like this:

someObject.setValue(someValue, forKey:"someKey")

But when I give the name of the method being called here, that name is setValue:forKey:. This choice has several advantages:

  • It is clear, compact, and predictable, being formed according to perfectly consistent and well-established rules.
  • For those who have been programming in Objective-C all these years, it’s what we’re used to. The way Objective-C methods are named is a thoroughly entrenched convention; even Swift programmers must accommodate themselves to seeing Objective-C method names plastered all over the Internet and Apple’s own documentation.
  • That name is in fact its name as far as Objective-C and the Cocoa APIs are concerned, and even in Swift you would need to know this. For example, if you wanted to specify this method when providing its name as a selector parameter (or as a string representing a selector), it is the Objective-C name that you would have to provide.
  • The translation from the Objective-C name into practical Swift syntax is mechanical and unambiguous — the first colon is replaced by parentheses embracing the first parameter plus the names and values of any remaining parameters — and is something that every Swift programmer needs to know how to do.

Similarly, I will speak of the setValue: parameter, even though, in an actual Swift method call, the name of that parameter appears before the parentheses, with no colon.

Apple has its own convention for saying the name of a Swift function, but, in this edition at least, I don’t use it. For example, Apple’s name for setValue:forKey: as a Swift function is setValue(_:forKey:). This has the advantage that it works even for Swift functions that don’t obey the Objective-C conventions for method names. But Apple’s own application of this convention is inconsistent — for example, the __FUNCTION__ literal sometimes obeys it and sometimes doesn’t — and it doesn’t help with the question of how to write a selector. My convention is about the names of Objective-C methods, so I give them Objective-C names.

My treatment of initializer names, however, is closer to Apple’s convention. Here, the difference between Objective-C and Swift is greater than a simple shorthand can readily encompass, so I give the initializer’s name as you would implement it. For example, in Objective-C, the default initializer for a UIView is initWithFrame:. In this book, I will call that initializer init(frame:). The same thing applies to what in Objective-C would be class factory methods with a corresponding initializer: when I want to mention what in Objective-C would be the UIImage class factory method imageNamed:, I’ll call it init(named:).

This treatment of initializer names has the great virtue that the name clarifies instantly that such a method is an initializer. Swift effectively abolishes class factory methods and brings such methods into the fold of formal initializers; my treatment of their names is a way of supporting and adopting that innovation.

Again, this convention requires some mental translation on the reader’s part, because in Swift the way you would name an initializer when you implement it is not the same as the way you would usually name it when you call it. If you were to override this method in a UIView subclass, you’d override init(frame:); but if you were to call it to create a new UIView, you’d say UIView(frame:). This mental translation, however, is hardly objectionable, as it is a practical fact to which every Swift user is already habituated.

Versions

This book was written using iOS 9 and Xcode 7, including Swift 2.0. (Just before publication, Apple released iOS 9.1, Xcode 7.1, and Swift 2.1, but this did not entail any changes in the book’s content.) In general, only very minimal attention is given to earlier versions of iOS and Xcode (and none at all to earlier versions of Swift). It is not my intention to embrace in this book any detailed knowledge about earlier versions of the software, which is, after all, readily and compendiously available in my earlier books. The book does contain, nevertheless, a few words of advice about backward compatibility, and now and then I will call out a particularly noteworthy change from earlier system versions, especially where your existing iOS 8 code is likely to break or behave differently when compiled against iOS 9.

Please bear in mind that Apple continues to make adjustments to the Swift language and to the way the Objective-C APIs are bridged to it. I have tried to keep my code up-to-date, but if, at some future time, a new version of Xcode is released along with a new version of Swift, some of the code in this book might be slightly incorrect. Please make allowances, and be prepared to compensate, for the possibility that my examples may contain slight occasional impedance mismatches, such as the lack of a needed Optional unwrap or the presence of a superfluous one.

Screenshots of Xcode were taken using Xcode 7 under OS X 10.10 Yosemite. I have not upgraded my machine to OS X 10.11 El Capitan, because at the time of this writing it was too new to be trusted with mission-critical work. If you are braver than I am and are running El Capitan, your interface may naturally look slightly different from the screenshots, but this difference will be minimal and shouldn’t cause any confusion.

Acknowledgments

My thanks go first and foremost to the people at O’Reilly Media who have made writing a book so delightfully easy: Rachel Roumeliotis, Sarah Schneider, Kristen Brown, Dan Fauxsmith, Adam Witwer, and Sanders Kleinfeld come particularly to mind. And let’s not forget my first and long-standing editor, Brian Jepson, who had nothing whatever to do with this edition, but whose influence is present throughout.

As in the past, I have been greatly aided by some fantastic software, whose excellences I have appreciated at every moment of the process of writing this book. I should like to mention, in particular:

The book was typed and edited entirely on my faithful Unicomp Model M keyboard (http://pckeyboard.com), without which I could never have done so much writing over so long a period so painlessly. For more about my physical work environment, see http://matt.neuburg.usesthis.com.

From the Programming iOS 4 Preface

A programming framework has a kind of personality, an overall flavor that provides an insight into the goals and mindset of those who created it. When I first encountered Cocoa Touch, my assessment of its personality was: “Wow, the people who wrote this are really clever!” On the one hand, the number of built-in interface objects was severely and deliberately limited; on the other hand, the power and flexibility of some of those objects, especially such things as UITableView, was greatly enhanced over their OS X counterparts. Even more important, Apple created a particularly brilliant way (UIViewController) to help the programmer make entire blocks of interface come and go and supplant one another in a controlled, hierarchical manner, thus allowing that tiny iPhone display to unfold virtually into multiple interface worlds within a single app without the user becoming lost or confused.

The popularity of the iPhone, with its largely free or very inexpensive apps, and the subsequent popularity of the iPad, have brought and will continue to bring into the fold many new programmers who see programming for these devices as worthwhile and doable, even though they may not have felt the same way about OS X. Apple’s own annual WWDC developer conventions have reflected this trend, with their emphasis shifted from OS X to iOS instruction.

The widespread eagerness to program iOS, however, though delightful on the one hand, has also fostered a certain tendency to try to run without first learning to walk. iOS gives the programmer mighty powers that can seem as limitless as imagination itself, but it also has fundamentals. I often see questions online from programmers who are evidently deep into the creation of some interesting app, but who are stymied in a way that reveals quite clearly that they are unfamiliar with the basics of the very world in which they are so happily cavorting.

It is this state of affairs that has motivated me to write this book, which is intended to ground the reader in the fundamentals of iOS. I love Cocoa and have long wished to write about it, but it is iOS and its popularity that has given me a proximate excuse to do so. Here I have attempted to marshal and expound, in what I hope is a pedagogically helpful and instructive yet ruthlessly Euclidean and logical order, the principles and elements on which sound iOS programming rests. My hope, as with my previous books, is that you will both read this book cover to cover (learning something new often enough to keep you turning the pages) and keep it by you as a handy reference.

This book is not intended to disparage Apple’s own documentation and example projects. They are wonderful resources and have become more wonderful as time goes on. I have depended heavily on them in the preparation of this book. But I also find that they don’t fulfill the same function as a reasoned, ordered presentation of the facts. The online documentation must make assumptions as to how much you already know; it can’t guarantee that you’ll approach it in a given order. And online documentation is more suitable to reference than to instruction. A fully written example, no matter how well commented, is difficult to follow; it demonstrates, but it does not teach.

A book, on the other hand, has numbered chapters and sequential pages; I can assume you know views before you know view controllers for the simple reason that Part I precedes Part II. And along with facts, I also bring to the table a degree of experience, which I try to communicate to you. Throughout this book you’ll find me referring to “common beginner mistakes”; in most cases, these are mistakes that I have made myself, in addition to seeing others make them. I try to tell you what the pitfalls are because I assume that, in the course of things, you will otherwise fall into them just as naturally as I did as I was learning. You’ll also see me construct many examples piece by piece or extract and explain just one tiny portion of a larger app. It is not a massive finished program that teaches programming, but an exposition of the thought process that developed that program. It is this thought process, more than anything else, that I hope you will gain from reading this book.

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values determined by context.

Tip

This element signifies a tip or suggestion.

Note

This element signifies a general note.

Warning

This element indicates a warning or caution.

Using Code Examples

Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/mattneub/Programming-iOS-Book-Examples.

This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Programming iOS 9 by Matt Neuburg (O’Reilly). Copyright 2016 Matt Neuburg, 978-1-491-93685-6.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

Safari® Books Online

Note

Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business.

Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training.

Safari Books Online offers a range of plans and pricing for enterprise, government, education, and individuals.

Members have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more information about Safari Books Online, please visit us online.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/programming_iOS9.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Get Programming iOS 9 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.