Tải bản đầy đủ

iOS 8 swift programming cookbook

Co
ve
rs

Use CloudKit APIs to store information in the cloud with ease

■■

Create custom keyboards and extensions

■■

Access users’ health-related information with HealthKit

■■

Interact with accessories inside the user’s home with HomeKit

■■

Create vibrant and lifelike user interfaces with UIKit Dynamics


■■

Use the Keychain to protect your app’s data

■■

Develop location-aware and multitasking-aware apps

■■

Work with iOS 8’s audio and video APIs

■■

Use Event Kit UI to manage calendars, dates, and events

■■

Take advantage of the accelerometer and the gyroscope

■■

Get working examples for implementing gesture recognizers

■■

Retrieve and manipulate contacts and groups from the
Address Book

■■

Determine a camera’s availability and access the Photo Library

complex requirements,
Vandad's iOS
Programming Cookbook
always provides me with
the resources I need and
good, clear, practical


examples. Now that I'm
starting out using Swift,
this edition is my Bible—I'd
have been lost without it.



—João Duarte

Senior iOS Software Engineer

US $59.99

Twitter: @oreillymedia
facebook.com/oreilly

Nahavandipoor

Vandad Nahavandipoor is an iOS and OS X programmer for an international
media group with over 7,000 employees in more than 29 countries. Previously
he worked for Lloyds Banking Group in England to deliver their iOS apps to millions
of users in the UK.

MOBILE DEVELOPMENT/IOS

e6

■■

od

You’ll find hundreds of new and revised recipes for using the iOS 8 SDK,
including techniques for working with Health app data and HomeKit
accessories, enhancing and animating graphics, storing and protecting
data, sending and receiving notifications, and managing files and folders.
Each recipe includes sample code on GitHub that you can use right away.

coding with new
“From
iOS features to tackling

iOS 8 Swift
Programming
Cookbook

Entirely rewritten for Apple’s Swift programming language, this updated
cookbook helps you overcome the vexing issues you’re likely to face when
creating apps for iOS devices.

Xc

iOS 8 Swift Programming Cookbook

iOS 8 Swift
Programming
Cookbook
SOLUTIONS & EXAMPLES FOR IOS APPS

CAN $62.99

ISBN: 978-1-491-90869-3

Vandad Nahavandipoor
www.it-ebooks.info


Co
ve
rs

Use CloudKit APIs to store information in the cloud with ease

■■

Create custom keyboards and extensions

■■

Access users’ health-related information with HealthKit

■■

Interact with accessories inside the user’s home with HomeKit

■■

Create vibrant and lifelike user interfaces with UIKit Dynamics

■■

Use the Keychain to protect your app’s data

■■

Develop location-aware and multitasking-aware apps

■■

Work with iOS 8’s audio and video APIs

■■

Use Event Kit UI to manage calendars, dates, and events

■■

Take advantage of the accelerometer and the gyroscope

■■

Get working examples for implementing gesture recognizers

■■

Retrieve and manipulate contacts and groups from the
Address Book

■■

Determine a camera’s availability and access the Photo Library

complex requirements,
Vandad's iOS
Programming Cookbook
always provides me with
the resources I need and
good, clear, practical
examples. Now that I'm
starting out using Swift,
this edition is my Bible—I'd
have been lost without it.



—João Duarte

Senior iOS Software Engineer

US $59.99

Twitter: @oreillymedia
facebook.com/oreilly

Nahavandipoor

Vandad Nahavandipoor is an iOS and OS X programmer for an international
media group with over 7,000 employees in more than 29 countries. Previously
he worked for Lloyds Banking Group in England to deliver their iOS apps to millions
of users in the UK.

MOBILE DEVELOPMENT/IOS

e6

■■

od

You’ll find hundreds of new and revised recipes for using the iOS 8 SDK,
including techniques for working with Health app data and HomeKit
accessories, enhancing and animating graphics, storing and protecting
data, sending and receiving notifications, and managing files and folders.
Each recipe includes sample code on GitHub that you can use right away.

coding with new
“From
iOS features to tackling

iOS 8 Swift
Programming
Cookbook

Entirely rewritten for Apple’s Swift programming language, this updated
cookbook helps you overcome the vexing issues you’re likely to face when
creating apps for iOS devices.

Xc

iOS 8 Swift Programming Cookbook

iOS 8 Swift
Programming
Cookbook
SOLUTIONS & EXAMPLES FOR IOS APPS

CAN $62.99

ISBN: 978-1-491-90869-3

Vandad Nahavandipoor
www.it-ebooks.info


iOS 8 Swift Programming
Cookbook

Vandad Nahavandipoor

www.it-ebooks.info


iOS 8 Swift Programming Cookbook
by Vandad Nahavandipoor
Copyright © 2015 Vandad Nahavandipoor. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com.

Editors: Andy Oram and Rachel Roumeliotis
Production Editor: Nicole Shelby
Proofreader: Gillian McGarvey
Indexer: Lucie Haskins
November 2014:

Cover Designer: Ellie Volckhausen
Interior Designer: David Futato
Illustrator: Rebecca Demarest

First Edition

Revision History for the First Edition:
2014-11-06:

First release

See http://oreilly.com/catalog/errata.csp?isbn=9781491908693 for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS 8 Swfit Programming Cookbook, the
cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark
claim, the designations have been printed in caps or initial caps.
While the publisher and the author have used good faith efforts to ensure that the information and instruc‐
tions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors
or omissions, including without limitation responsibility for damages resulting from the use of or reliance
on this work. Use of the information and instructions contained in this work is at your own risk. If any code
samples or other technology this work contains or describes is subject to open source licenses or the intel‐
lectual property rights of others, it is your responsibility to ensure that your use thereof complies with such
licenses and/or rights.

ISBN: 978-1-491-90869-3
[Malloy]

www.it-ebooks.info


Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
1. The Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1. Adding Blur Effects to Your Views
1.2. Presenting Temporary Information on the Screen with Popovers
1.3. Displaying Images with UIImageView
1.4. Displaying Static Text with UILabel
1.5. Adding Buttons to the User Interface with UIButton
1.6. Displaying Alerts and Action Sheets
1.7. Creating, Using, and Customizing Switches with UISwitch
1.8. Picking Values with the UIPickerView
1.9. Picking the Date and Time with UIDatePicker
1.10. Implementing Range Pickers with UISlider
1.11. Grouping Compact Options with UISegmentedControl
1.12. Presenting Sharing Options with UIActivityViewController
1.13. Presenting Custom Sharing Options with UIActivityViewController
1.14. Displaying an Image on a Navigation Bar
1.15. Adding Buttons to Navigation Bars Using UIBarButtonItem
1.16. Accepting User Text Input with UITextField
1.17. Displaying Long Lines of Text with UITextView
1.18. Creating Scrollable Content with UIScrollView
1.19. Loading Web Pages with WebKit
1.20. Loading Web Pages with UIWebView
1.21. Displaying Progress with UIProgressView
1.22. Creating a Provision Profile

9
12
17
21
27
31
37
41
46
49
53
57
63
68
70
75
83
88
91
94
97
99

2. Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
2.1. Adding New Photo Editing Capabilities to the Photos App
2.2. Providing a Custom Sharing Extension to iOS

110
118

iii

www.it-ebooks.info


2.3. Building Custom Keyboards
2.4. Creating a Service Within Your App with Action Extensions
2.5. Adding Widgets to the Notification Center

129
137
144

3. Managing Health Data with HealthKit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
3.1. Setting Up Your App for HealthKit
3.2. Retrieving and Modifying the User’s Weight Information
3.3. Accessing and Modifying the User’s Height Information
3.4. Retrieving User Characteristics
3.5. Observing Changes to the User’s Health Information
3.6. Reading and Modifying the User’s Total Calories Burned
3.7. Converting Between Units

155
160
165
172
177
183
196

4. Managing Home Appliances with HomeKit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
4.1. Simulating HomeKit Accessories
4.2. Managing the User’s Home in HomeKit
4.3. Adding Rooms to the User’s Home
4.4. Specifying Zones in the User’s Home
4.5. Discovering and Managing HomeKit Enabled Accessories
4.6. Interacting with HomeKit Accessories
4.7. Grouping Services of HomeKit Accessories

203
212
219
224
229
234
242

5. Creating Dynamic and Interactive User Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
5.1. Adding Gravity to Your UI Components
5.2. Detecting and Reacting to Collisions Between UI Components
5.3. Animating Your UI Components with a Push
5.4. Attaching Multiple Dynamic Items to Each Other
5.5. Adding a Dynamic Snap Effect to Your UI Components
5.6. Assigning Characteristics to Your Dynamic Effects

249
250
257
262
266
269

6. Table and Collection Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
6.1. Populating a Table View with Data
6.2. Enabling Swipe Deletion of Table View Cells
6.3. Constructing Headers and Footers in Table Views
6.4. Displaying a Refresh Control for Table Views
6.5. Providing Basic Content to a Collection View
6.6. Feeding Custom Cells to Collection Views Using .xib Files
6.7. Handling Events in Collection Views
6.8. Providing Header and Footer in a Collection View
6.9. Adding Custom Interactions to Collection Views

iv

|

Table of Contents

www.it-ebooks.info

277
281
282
288
292
297
303
307
312


7. Concurrency and Multitasking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
7.1. Performing UI-Related Tasks
7.2. Performing Non-UI Related Tasks
7.3. Performing Tasks After a Delay
7.4. Performing a Task Only Once
7.5. Grouping Tasks Together
7.6. Creating Simple Concurrency with Operations
7.7. Creating Dependency Between Operations
7.8. Firing Periodic Tasks
7.9. Completing a Long-Running Task in the Background
7.10. Adding Background Fetch Capabilities to Your Apps
7.11. Playing Audio in the Background
7.12. Handling Location Changes in the Background
7.13. Handling Network Connections in the Background

319
321
329
331
332
335
340
342
345
348
357
360
363

8. Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
8.1. Authenticating the User with Touch ID
8.2. Enabling Security and Protection for Your Apps
8.3. Storing Values in the Keychain
8.4. Finding Values in the Keychain
8.5. Updating Existing Values in the Keychain
8.6. Deleting Existing Values in the Keychain
8.7. Sharing Keychain Data Between Multiple Apps
8.8. Writing to and Reading Keychain Data from iCloud
8.9. Storing Files Securely in the App Sandbox
8.10. Securing Your User Interface

373
376
381
383
386
390
392
397
399
403

9. Core Location, iBeacon, and Maps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
9.1. Detecting Which Floor the User Is on in a Building
9.2. Defining and Processing iBeacons
9.3. Pinpointing the Location of a Device
9.4. Displaying Pins on a Map View
9.5. Displaying Custom Pins on a Map View
9.6. Searching on a Map View
9.7. Displaying Directions on the Map
9.8. Customizing the View of the Map with a Camera

407
409
415
420
423
429
434
440

10. Gesture Recognizers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
10.1. Detecting Swipe Gestures
10.2. Detecting Rotation Gestures
10.3. Detecting Panning and Dragging Gestures
10.4. Detecting Long Press Gestures

447
449
452
455

Table of Contents

www.it-ebooks.info

|

v


10.5. Detecting Tap Gestures
10.6. Detecting Pinch Gestures
10.7. Detecting Screen Edge Pan Gestures

458
460
462

11. Networking and Sharing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
11.1. Downloading Data Using NSURLSession
11.2. Downloading Data in the Background Using NSURLSession
11.3. Uploading Data Using NSURLSession
11.4. Downloading Asynchronously with NSURLConnection
11.5. Handling Timeouts in Asynchronous Connections
11.6. Downloading Synchronously with NSURLConnection
11.7. Customizing URL Requests
11.8. Sending HTTP Requests with NSURLConnection
11.9. Serializing and Deserializing JSON Objects
11.10. Integrating Social Sharing into Your Apps

465
473
477
479
483
484
487
488
491
495

12. Multimedia. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
12.1. Playing Audio Files
12.2. Recording Audio
12.3. Playing Video Files
12.4. Capturing Thumbnails from Video Files
12.5. Accessing the Music Library

499
501
509
513
516

13. Address Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
13.1. Retrieving a Person Entity with System UI
13.2. Retrieving a Property of a Person Entity with System UI
13.3. Requesting Access to the Address Book
13.4. Retrieving All the People in the Address Book
13.5. Retrieving Properties of Address Book Entries
13.6. Inserting a Person Entry into the Address Book
13.7. Inserting a Group Entry into the Address Book
13.8. Adding Persons to Groups
13.9. Searching the Address Book
13.10. Retrieving and Setting a Person’s Address Book Image

527
531
534
537
538
541
544
547
549
552

14. Files and Folder Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
14.1. Finding the Paths of the Most Useful Folders on Disk
14.2. Writing to and Reading from Files
14.3. Creating Folders on Disk
14.4. Enumerating Files and Folders
14.5. Deleting Files and Folders
14.6. Saving Objects to Files

vi

|

Table of Contents

www.it-ebooks.info

557
559
564
565
571
574


15. Camera and the Photo Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
15.1. Detecting and Probing the Camera
15.2. Taking Photos with the Camera
15.3. Taking Videos with the Camera
15.4. Storing Photos in the Photo Library
15.5. Storing Videos in the Photo Library
15.6. Searching for and Retrieving Images and Videos
15.7. Reacting to Changes in Images and Videos
15.8. Editing Images and Videos Right on the Device

579
583
587
590
595
597
602
608

16. Notifications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
16.1. Sending Notifications
16.2. Listening for and Reacting to Notifications
16.3. Listening and Reacting to Keyboard Notifications
16.4. Scheduling Local Notifications
16.5. Listening for and Reacting to Local Notifications
16.6. Handling Local System Notifications
16.7. Setting Up Your App for Push Notifications
16.8. Delivering Push Notifications to Your App
16.9. Reacting to Push Notifications

616
618
621
630
636
639
642
648
656

17. Core Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
17.1. Performing Batch Updates on Core Data
17.2. Writing to Core Data
17.3. Reading Data from Core Data
17.4. Deleting Data from Core Data
17.5. Sorting Data in Core Data
17.6. Boosting Data Access in Table Views
17.7. Implementing Relationships in Core Data
17.8. Fetching Data in the Background
17.9. Using Custom Data Types in Your Core Data Model

661
664
666
668
670
672
680
686
690

18. Dates, Calendars, and Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
18.1. Constructing Date Objects
18.2. Retrieving Date Components
18.3. Requesting Permission to Access Calendars
18.4. Retrieving Calendar Groups on an iOS Device
18.5. Adding Events to Calendars
18.6. Accessing the Contents of Calendars
18.7. Removing Events from Calendars
18.8. Adding Recurring Events to Calendars
18.9. Retrieving the Attendees of an Event

698
699
700
705
707
712
714
718
722

Table of Contents

www.it-ebooks.info

|

vii


18.10. Adding Alarms to Calendars

725

19. Graphics and Animations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729
19.1. Drawing Text
19.2. Drawing Images
19.3. Constructing Resizable Images
19.4. Drawing Lines
19.5. Constructing Paths
19.6. Drawing Rectangles
19.7. Adding Shadows to Shapes
19.8. Drawing Gradients
19.9. Transforming Views
19.10. Animating Views

734
736
739
745
751
755
759
764
770
776

20. Core Motion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
20.1. Retrieving Altitude Data
20.2. Retrieving Pedometer Data
20.3. Detecting the Availability of an Accelerometer
20.4. Detecting the Availability of a Gyroscope
20.5. Retrieving Accelerometer Data
20.6. Detecting Shakes on an iOS Device
20.7. Retrieving Gyroscope Data

788
790
794
796
797
801
802

21. Cloud. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
21.1. Setting Up Your App for CloudKit
21.2. Storing Data with CloudKit
21.3. Retrieving Data with CloudKit
21.4. Querying the Cloud with CloudKit
21.5. Observing Changes to Records in CloudKit
21.6. Retrieving User Information from CloudKit
21.7. Storing and Synchronizing Dictionaries in iCloud
21.8. Creating and Managing Files and Folders in iCloud
21.9. Searching for Files and Folders in iCloud

807
812
820
826
831
839
846
851
855

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 863

viii

|

Table of Contents

www.it-ebooks.info


Preface

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 Con‐
ference (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 develop‐
ment, 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
ix

www.it-ebooks.info


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 under‐
stand 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.

Audience
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 thor‐
oughly 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.

x

|

Preface

www.it-ebooks.info


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 func‐
tionality 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.

Preface

www.it-ebooks.info

|

xi


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 authen‐
tication 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.

xii

|

Preface

www.it-ebooks.info


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, dis‐
play 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.

Preface

www.it-ebooks.info

|

xiii


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 doc‐
umentation 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 devel‐
oping 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:
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 deter‐
mined by context.
This icon signifies a tip, suggestion, or general note.

xiv

|

Preface

www.it-ebooks.info


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 ex‐
ample 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 permissions@oreilly.com.

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 crea‐
tive professionals use Safari Books Online as their primary resource for research, prob‐
lem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi‐
zations, 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 Pro‐
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT

Preface

www.it-ebooks.info

|

xv


Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐
ogy, 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 bookques
tions@oreilly.com.
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

Acknowledgments
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.
xvi

|

Preface

www.it-ebooks.info


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”!

Preface

www.it-ebooks.info

|

xvii


www.it-ebooks.info


CHAPTER 1

The Basics

1.0. Introduction
In order to write apps for iOS, you need to know some of the basics of the Swift pro‐
gramming language that we will use throughout this book. Swift is Apple’s new pro‐
gramming language introduced in Xcode 6 and iOS 8 SDK. Objects and classes are
fundamental in object-oriented programming (OOP) languages such as Swift,
Objective-C, Java, C++, and many others.
All iOS applications essentially use the model-view-controller (MVC) architecture.
Model, view, and controller are the three main components of an iOS application from
an architectural perspective.
The model is the brain of the application. It does the calculations and creates a virtual
world for itself that can live without the views and controllers. In other words, think of
a model as a virtual copy of your application, without a face!
A view is the window through which your users interact with your application. It displays
what’s inside the model most of the time, but in addition to that, it accepts users’ inter‐
actions. Any interaction between the user and your application is sent to a view, which
then can be captured by a view controller and sent to the model.
The controller in iOS programming usually refers to the view controllers I just men‐
tioned. Think of a view controller as a bridge between the model and your views. This
controller interprets what is happening on one side and uses that information to alter
the other side as needed. For instance, if the user changes a field in a view, the controller
makes sure the model changes in response. And if the model gets new data, the controller
tells the view to reflect it.
In this chapter, you will learn how to create the structure of an iOS application and how
to use views and view controllers to create intuitive applications.

1

www.it-ebooks.info


I also want to teach you a few basics of the Swift programming language—but before
we begin, I want to make it absolutely obvious that the goal of this book is not to teach
you how to program in Swift. Apple has already released a full book more than 500
pages long that teaches you how to use Swift. But in case you’re using this book in parallel
with some other resource to learn Swift, I will go over a few basics.

Defining Constants and Variables in Swift
We define constants with the let keyword like so:
let integerValue = 10
let stringValue = "Swift"
let doubleValue = 10.0

The value that we assign to a constant (or later to a variable) defines its type. In the
examples I gave, we did not have to define the data type of the constants at all because
the Swift compiler can figure out the proper type from the values we assigned. However,
if you want to define the data type manually, you can do so using the following syntax:
let integerFromDouble = 10.7 as Int
/* The value of this variable is 10
because the compiler truncated the value to an integer*/

When a constant is defined and a value is assigned to it, it cannot be changed later. If
you need to change a value, use a variable instead, with the var keyword:
var myString = "Swi"
myString += "ft"
/* myString is now "Swift" */

Variables can be mutable or immutable. An immutable variable cannot be changed or
appended to. Mutable variables can be changed.

Creating and Using Arrays in Swift
The [DataType] syntax can create an array. This is an example of creating an immutable
array:
let allStrings = ["Swift", "Objective-C"]

If you want to create a mutable array, initialize an empty mutable array and then append
values to it like so. Use var so your allStrings array is a variable, not a constant:
var allStrings = [String]()
allStrings.append("Swift")
allStrings.append("Objective-C")
/* Our array is now ["Swift", "Objective-C" */

If you want to access values inside an array, use subscripting with the [] syntax:
var allStrings = [String]()
allStrings.append("Swift")

2

|

Chapter 1: The Basics

www.it-ebooks.info


allStrings.append("Objective-C")
println(allStrings[0]) /* Prints out "Swift" */
allStrings.insert("C++", atIndex: 0)
println(allStrings[0]) /* Prints out "C++" */

Defining and Accessing Dictionaries in Swift
A dictionary is a hash table. Each entry in a dictionary specifies one object as a key and
another object as its value. Dictionaries in Swift are dynamically typed, based on what
we feed them, and are created with the [key: value] syntax, as shown here:
let allFullNames = [
"Vandad" : "Nahavandipoor",
"Andy"
: "Oram",
"Molly" : "Lindstedt"
]

To access the value of a key, use subscripting like so:
println(allFullNames["Vandad"]) /* Prints out "Nahavandipoor" */

The dictionary that we created was immutable because of the let keyword. To create a
mutable version of the same dictionary, use the var keyword like so:
var allFullNames = [
"Vandad" : "Nahavandipoor",
"Andy"
: "Oram",
"Molly"
: "Lindstedt"
]
allFullNames["Rachel"] = "Roumeliotis"

This dictionary is of type [String: String] because of the values that we provided to
it. You can add any type of value or key to the dictionary to see how the data type changes:
let personInformation = [
"numberOfChildren" : 2,
"age"
: 32,
"name"
: "Random person",
"job"
: "Something cool",
] as [String : AnyObject]

The AnyObject type, as its name implies, represents an instance of any class type. In this
case, we are saying that the keys to our dictionary are strings but the values are a mix
of various class types. Dictionaries and arrays in Swift can be freely bridged to their
Cocoa Touch counterparts of NSDictionary and NSArray.

1.0. Introduction

www.it-ebooks.info

|

3


Grouping Functionality with Classes and Structures in Swift
Structures are value types. That means that when they are passed around from one
function to another, for instance, a new instance of them is created and then passed to
the function. Classes are reference types, so that they can be passed around without
having to be copied.
Imagine having the following structure:
struct Person{
var firstName, lastName: String
mutating func setFirstNameTo(firstName: String){
self.firstName = firstName
}
}

This structure has a method that can cause the structure to mutate, so it is prefixed with
the keyword mutating. Now we can create a function that can change the value of any
Person instance to any given string:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func changeFirstNameOf(var person: Person, to: String){
person.setFirstNameTo(to)
/* person.firstName is VANDAD now and only in this function */
}
func application(application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [NSObject : AnyObject]?) -> Bool {
var vandad = Person(firstName: "Vandad", lastName: "Nahavandipoor")
changeFirstNameOf(vandad, to: "VANDAD")
/* vandad.firstName is still Vandad */
return true
}
}

Note that the value of the firstName property of the person instance is changed only
in the context of the function, not outside it. That means when the instance of the Person
structure was passed to the function to change the first name to a given string, the
structure as a whole was copied into the stack and passed to the function. Therefore,
even though we called the mutating function on it, the first name of the vandad variable
did not change.
4

|

Chapter 1: The Basics

www.it-ebooks.info


Now off to classes. Classes are reference types and when passed to functions, are passed
just as references to a single copy held in memory. Have a look at the following example:
class Person{
var (firstName, lastName) = ("", "")
init (firstName: String, lastName: String){
self.firstName = firstName
self.lastName = lastName
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func changeFirstNameOf(person: Person, to: String){
person.firstName = to
}
func application(application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [NSObject : AnyObject]?) -> Bool {
var vandad = Person(firstName: "Vandad", lastName: "Nahavandipoor")
changeFirstNameOf(vandad, to: "VANDAD")
/* vandad.firstName is now VANDAD */
return true
}
}

You can see that the first name of the vandad variable is indeed changed in its original
context after it was passed to a function that changed the first name. Classes can also
have inheritance, but structures cannot have inheritance.

Diving into Operators in Swift
There are many valid operators in Swift. Here are a few examples:
typealias byte = UInt8
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
/* Bitwise OR operator */

1.0. Introduction

www.it-ebooks.info

|

5


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×