O'Reilly logo

iOS 8 Swift Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required


About a year ago, noticing that Apple had not updated Objective-C much over the past few years, I got intimations that they were working on a new language or framework for iOS development, and even suggested it to my friends at work. They laughed and said, “Then you will have to write your book from scratch.” They were right; this edition is almost a whole new book.

The previous edition of the book had already seemed like a very big job because I added so many recipes as well as updated all the Objective-C code for iOS 7. But the task was dwarfed by this edition, where everything had to be rewritten in Swift. Furthermore, so many recipes are new that I have lost count. I can affirm that this edition of the book is the most extensive effort since my initial effort to write the first edition. All the code has been written in Swift. Not just translated line by line, but rewritten to take advantage of awesome features in Swift, like extensions.

None of us quite expected Swift to come out from Apple’s Worldwide Developers Conference (WWDC) 2014. We thought it would be a normal WWDC with tons of new APIs and just some additions to Objective-C like previous years at WWDC. But we were all surprised. At least I was.

I think Swift is a great language and has been needed for iOS development for a long time. Those of us who grew up with the first iOS SDK or—as it was called back then—the iPhone SDK, know how painful it was to do reference counting manually. Explaining those concepts in early editions of this book, I felt they were sometimes unnecessary and “got in the way” when developing iOS apps. Instead of focusing on writing great apps, we had to focus much of our attention on writing apps that wouldn’t crash because of memory management issues. Swift has fixed a lot of those issues and has left us with a lot more complicated things to deal with.

Swift seems like a programming language that is intended for more than iOS development, because so many of its features are unneeded in basic applications and are more appropriate for something complicated and demanding such as a game. When it comes to iOS development, the frameworks seem to be more important than the language, and the frameworks are usually what we struggle with. The difficulty is exacerbated by a lack of documentation for APIs. Many development companies, Apple included, seem to think they can just put out documentation for each API in isolation. They don’t understand that programmers need to use a series of APIs together to achieve something. Apple tells you: here is a carrot, it has X number of calories, it weighs this much, its color is orange, and it has been produced in this country. This book tells you: here is a carrot and this is how you can make a carrot soup with it.

Apple doesn’t provide basic instructions on how to use their APIs. But they are not alone in this. It is a very big job to document the APIs and they have done a great job with that. I will help you use those APIs to deliver amazing apps to your customers.

I hope you’ll enjoy reading this book, and if there is anything that I have not explained, you can contact me through Facebook or Twitter or just send me an email. I will be more than happy to help fellow developers out.


I assume you know your way around Xcode and have written a few lines of Swift code before. This book does not offer a tutorial about how to write Swift code, but will show you interesting and powerful iOS apps using Swift. There is a big difference. I don’t explain the Swift language in this book, because Apple has already done that quite thoroughly with the Swift Programming Language guide, which is about 500 pages long! There is no need for a book to re-explain what Apple has already explained. So if you are not comfortable with Swift yet, I suggest that you read the aforementioned guide published and made freely available by Apple—just do a web search.

This book is also not going to teach you the very basics of iOS development. I expect you to know the basics of software engineering and algorithms. Please do not purchase this book in the hopes that it will make you a software engineer, because that is not its goal. If you already know about functions, the stack, arrays, dictionaries or hash-tables, etc., this book is good for you. Otherwise, I suggest that you first become a software engineer of some sort (even if your language is not Swift), and then pick this book up to learn how to write awesome iOS apps.

Organization of This Book

Here is a concise breakdown of the material each chapter covers:

Chapter 1, The Basics

This chapter explains the fundamental building blocks of iOS development, such as messages, labels, sliders, buttons, text fields and views, navigation bars, etc. I suggest that you read the recipes in this chapter and try them out before moving on to more advanced subjects.

Chapter 2, Extensions

Finally! Apple allows us to extend iOS with these little binaries that ship with our apps, get integrated into iOS, and can live by themselves without the need for our apps to be running in the background. For instance, we can now create custom keyboards that can get installed on the user’s device and the user can use those keyboards even if our app is not running. This feature has been in Android pretty much since its beginning, so when Apple allowed this feature on iOS, I said not “Oh, great” but “Finally.” Have a look at this chapter and make up your own mind about its value for you.

Chapter 3, Managing Health Data with HealthKit

The HealthKit framework allows iOS apps to integrate with the health-information that is stored on the user’s device. This information belongs to the current user of the device and can contain very detailed information, such as the amount of fat that the user burned in the last running session they did. This chapter teaches you how to integrate your apps with HealthKit and read and write to this health database.

Chapter 4, Managing Home Appliances with HomeKit

HomeKit is another awesome framework in the SDK. It allows iOS apps to speak to accessories that are HomeKit enabled, so to speak. You will learn to discover these accessories, configure them, talk to them, and so on.

Chapter 5, Creating Dynamic and Interactive User Interfaces

Creating a lively user interface takes more than a table view and a label placed on a navigation bar! You need to simulate real-life physics. This chapter teaches you such things as how to model gravity and other dynamic behaviors, and how to attach those to your UI components.

Chapter 6, Table and Collection Views

A lot of the information that we want to display to the user is hierarchichal, in that it can be separated into specific cells on the screen and eventually displayed to the user. Table views and collection views are used pretty much everywhere in iOS. From the Photos app to the Settings, you can see collection and table views at work everywhere. This chapter teaches you all you need to know to create great functionality with these components in the SDK.

Chapter 7, Concurrency and Multitasking

When your app runs, by default, you will be on the main thread in your app delegate so that you can perform UI-related tasks. But you do not want to perform heavy downloading tasks and heavy calculations on the UI thread because you’ll trash your users’ experience. In fact, iOS will actually kill your app if you block the UI thread for more than five seconds. Concurrency and multithreading is taught in this chapter to allow you to create fluid apps that do all the work they need, without stepping on the UI thread too much.

Chapter 8, Security

Do you store usernames and passwords using NSUserDefaults? If your answer is yes, you desperately need to read this chapter. We will talk about Touch ID authentication and many Keychain-related functionalities. You will also learn how to make your user interfaces more secure.

Chapter 9, Core Location, iBeacon, and Maps

All the sensors in an iOS device are helpful when you try to find your way to the supermarket or find out which floor of a building you are currently on (seriously, iOS almost always knows this). So you can learn about iBeacons and maps and core location in this chapter.

Chapter 10, Gesture Recognizers

When Steve Jobs introduced the iPhone, he showed the world how to scroll through an iPod music library by swiping up and down the page. I still remember people clapping and going “Ooooh.” Apple engineers had placed a swipe gesture on the view, which allowed Mr. Jobs to scroll up and down the page so smoothly. This chapter teaches you all about gestures.

Chapter 11, Networking and Sharing

What is an iOS device with no Internet connection? A simple phone or a tablet. Network connectivity really adds another dimension to smartphones. This chapter teaches you how to do background and foreground networking to download and upload files using various classes in the SDK.

Chapter 12, Multimedia

Inside an iOS app, with the user’s permission, you can access their audio and video files and play those files for the user, or simply grab the data for those files for whatever processing you need to do. If you are creating a game, for instance, you might want to play some background music for the user to add some excitement to your game. This chapter teaches you how to load and play audio and video files.

Chapter 13, Address Book

The Address Book framework still consists of C APIs. Some people say this is for performance reasons, but I believe Apple has just assigned a low priority to the framework and they just have not brought it up to date with the latest technologies in the SDK. So this chapter teaches you how to use Swift to integrate the Address Book framework into your apps in order to access the user’s contacts’ information, after the user has given you permission to do so.

Chapter 14, Files and Folder Management

You can easily write iOS apps that do not need to work with files and folders. But as soon as you find the need to store information in files and categorize them into folders, you can start reading this chapter. I will teach you how to write to files, read from them, enumerate them, and so on.

Chapter 15, Camera and the Photo Library

iOS keeps a library of all the videos and photos that the user has on her device. The app that allows the user to see these photos and videos is called Photos (obviously!). In this chapter, we will learn how to access the raw data for the photos and videos stored on the device, so that you can integrate this functionality into your apps without having to redirect the user to the Photos app.

Chapter 16, Notifications

Different parts of iOS interact with each other through notifications. For instance, when the app goes to the background, iOS sends a notification into your application memory space. You can catch this notification in any object inside your app to get notified when the app has gone to the background, in order to do whatever there is that you want to do. This chapter teaches you all about local, push, and app notifications.

Chapter 17, Core Data

Core Data is Apple’s database technology. You can store data, read it back, sort it, display it, create relationships between different pieces of data, and so on. What is there not to like? Core Data is an amazingly simple technology but requires a certain understanding of its underlying architecture. I will walk you through that in this chapter.

Chapter 18, Dates, Calendars, and Events

Dates are important, whether we are talking about editable dates or a date with a partner-to-be or just dates as they are in a calendar. Even though I won’t be handing out dating advice, you can learn about calendar dates in this chapter. You will learn to construct date objects, read events from the user’s calendar, and so on.

Chapter 19, Graphics and Animations

Every now and then you might want to impress your users with some cool graphics and animations. This chapter is all about that. You can draw images on the screen, animate them, rotate them, and so on. Dazzle your users.

Chapter 20, Core Motion

A pedometer is a wonderful device that can count the user’s steps-taken from time to time. As soon as you have the user’s steps data and you know their age and other simple information, you can start counting the calories that they are burning, display them motivating messages, and so on. In this chapter you will learn about the pedometer, accelerometer, and gyroscope, which are some great sensors that Apple has built into pretty much all iOS devices in the market today.

Chapter 21, Cloud

Imagine being able to store data in the cloud just as easily as you would store data in Core Data. CloudKit allows you to do precisely that. It is another layer on top of iCloud. You will also learn about iCloud in this chapter.

Additional Resources

Swift is a relatively new language with which you’ll want to familiarize yourself if you care about iOS development. As I mentioned before, I recommend that you read Apple’s guide on the Swift Programming Language. You won’t be disappointed.

From time to time, I refer to official Apple documentation. Some of Apple’s descriptions are right on the mark, and there is no point in trying to restate them. Throughout this book, I have listed the most important documents and guides in the official Apple documentation that every professional iOS developer should read.

For starters, I suggest that you have a look at the iOS Human Interface Guidelines for all iOS devices. This document will tell you everything you need to know about developing engaging and intuitive user interfaces for all iOS devices. Every iOS programmer should read this document. In fact, I believe this should be required reading for the product design and development teams of any company that develops iOS applications.

I also suggest that you skim through the “iOS App Programming Guide” in the iOS Developer Library for some tips and advice on how to make great iOS applications.

Conventions Used in This Book

The following typographical conventions are used in this book:


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.


This icon signifies a tip, suggestion, or general note.


This icon indicates a warning or caution.

Using Code Examples

Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/vandadnp/iOS-8-Swift-Programming-Cookbook.

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: “iOS 8 Swift Programming Cookbook by Vandad Nahavandipoor (O’Reilly). Copyright 2014 Vandad Nahavandipoor, 978-1-4919-0869-3.”

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

Safari® Books Online


Safari Books Online (www.safaribooksonline.com) 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 product mixes and pricing programs for organizations, government agencies, and individuals. Subscribers 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 dozens 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/ios8-swift-prog-ckbk.

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


Andy Oram, as always, has been such an amazing editor for this edition of the book. He has worked at the speed of light to deliver this material to you. He has gone through everything that I’ve written, word by word, and has ensured that my content is digestible by a much wider audience than I could ever imagine writing for. I thank you for your hard work. Thank you to Niklas Saers, who did a great job technically reviewing this book.

Rachel Roumeliotis has also been a fantastic help at O’Reilly. She has supported me throughout my work. She was very happy when I decided to rewrite this book for Swift so it is great having her on my side when the time came to make a big decision like that.

Thanks to Sara, my lovely partner, for her patience while I wrote this book. I cannot imagine having a more loving and patient partner. I genuinly appreciate all you’ve done for me throughout this period.

Also thank you to Heather Scherer and Amy Jollymore of O’Reilly for sorting out many aspects of this book and my upcoming video series. I appreciate your help.

Thanks to Ulla, Leif, Bella, David, and the kids for every second we spend together. These times mean a lot to me and I am forever grateful. Last but not least, I want to acknowledge Molly’s presence and support as well and for the lovely faces that she gives me every day when we go on walks. Even though you are quite a lot of work, I still love you. “Duktig tjej”!

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required