Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Tài liệu đang bị lỗi
File tài liệu này hiện đang bị hỏng, chúng tôi đang cố gắng khắc phục.
ios 7 programming cookbook
Nội dung xem thử
Mô tả chi tiết
www.it-ebooks.info
www.it-ebooks.info
Vandad Nahavandipoor
iOS 7 Programming Cookbook
www.it-ebooks.info
iOS 7 Programming Cookbook
by Vandad Nahavandipoor
Copyright © 2014 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://my.safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or [email protected].
Editors: Andy Oram and Rachel Roumeliotis
Production Editor: Christopher Hearse
Copyeditor: Zyg Group, LLC
Proofreader: Julie Van Keuren
Indexer: Angela Howard
Cover Designer: Randy Comer
Interior Designer: David Futato
Illustrator: Rebecca Demarest
October 2013: First Edition
Revision History for the First Edition:
2013-10-09: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781449372422 for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc., iOS 7 Programming Cookbook, the image of a Cowan’s shrew tenrec, 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 trade‐
mark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
ISBN: 978-1-449-37242-2
[QG]
www.it-ebooks.info
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1. Implementing Controllers and Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1. Displaying Alerts with UIAlertView 23
1.2. Creating and Using Switches with UISwitch 32
1.3. Customizing the UISwitch 36
1.4. Picking Values with the UIPickerView 39
1.5. Picking the Date and Time with UIDatePicker 45
1.6. Implementing Range Pickers with UISlider 50
1.7. Customizing the UISlider 54
1.8. Grouping Compact Options with UISegmentedControl 59
1.9. Presenting and Managing Views with UIViewController 63
1.10. Presenting Sharing Options with UIActivityViewController 67
1.11. Presenting Custom Sharing Options with UIActivityViewController 73
1.12. Implementing Navigation with UINavigationController 79
1.13. Manipulating a Navigation Controller’s Array of View Controllers 85
1.14. Displaying an Image on a Navigation Bar 86
1.15. Adding Buttons to Navigation Bars Using UIBarButtonItem 88
1.16. Presenting Multiple View Controllers with UITabBarController 94
1.17. Displaying Static Text with UILabel 101
1.18. Customizing the UILabel 105
1.19. Accepting User Text Input with UITextField 108
1.20. Displaying Long Lines of Text with UITextView 118
1.21. Adding Buttons to the User Interface with UIButton 123
1.22. Displaying Images with UIImageView 127
1.23. Creating Scrollable Content with UIScrollView 132
1.24. Loading Web Pages with UIWebView 137
1.25. Displaying Progress with UIProgressView 141
1.26. Constructing and Displaying Styled Texts 143
iii
www.it-ebooks.info
1.27. Presenting Master-Detail Views with UISplitViewController 148
1.28. Enabling Paging with UIPageViewController 153
1.29. Displaying Popovers with UIPopoverController 158
2. Creating Dynamic and Interactive User Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
2.1. Adding Gravity to Your UI Components 171
2.2. Detecting and Reacting to Collisions Between UI Components 172
2.3. Animating Your UI Components with a Push 180
2.4. Attaching Multiple Dynamic Items to Each Other 184
2.5. Adding a Dynamic Snap Effect to Your UI Components 189
2.6. Assigning Characteristics to Your Dynamic Effects 192
3. Auto Layout and the Visual Format Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
3.1. Placing UI Components in the Center of the Screen 201
3.2. Defining Horizontal and Vertical Constraints with the Visual Format
Language 203
3.3. Utilizing Cross View Constraints 210
3.4. Configuring Auto Layout Constraints in Interface Builder 217
4. Constructing and Using Table Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
4.1. Populating a Table View with Data 225
4.2. Using Different Types of Accessories in a Table View Cell 229
4.3. Creating Custom Table View Cell Accessories 232
4.4. Enabling Swipe Deletion of Table View Cells 235
4.5. Constructing Headers and Footers in Table Views 237
4.6. Displaying Context Menus on Table View Cells 246
4.7. Moving Cells and Sections in Table Views 251
4.8. Deleting Cells and Sections from Table Views 257
4.9. Utilizing the UITableViewController for Easy Creation of Table Views 268
4.10. Displaying a Refresh Control for Table Views 274
5. Building Complex Layouts with Collection Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
5.1. Constructing Collection Views 281
5.2. Assigning a Data Source to a Collection View 284
5.3. Providing a Flow Layout to a Collection View 285
5.4. Providing Basic Content to a Collection View 288
5.5. Feeding Custom Cells to Collection Views Using .xib Files 294
5.6. Handling Events in Collection Views 299
5.7. Providing a Header and a Footer in a Flow Layout 303
5.8. Adding Custom Interactions to Collection Views 308
iv | Table of Contents
www.it-ebooks.info
5.9. Providing Contextual Menus on Collection View Cells 311
6. Storyboards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
6.1. Adding a Navigation Controller to a Storyboard 316
6.2. Passing Data from One Screen to Another 318
6.3. Adding a Tab Bar Controller to a Storyboard 325
6.4. Introducing Custom Segue Transitions to Your Storyboard 328
6.5. Placing Images and Other UI Components on Storyboards 332
7. Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
7.1. Constructing Block Objects 342
7.2. Accessing Variables in Block Objects 346
7.3. Invoking Block Objects 352
7.4. Performing UI-Related Tasks with GCD 354
7.5. Executing Non-UI Related Tasks Synchronously with GCD 358
7.6. Executing Non-UI Related Tasks Asynchronously with GCD 361
7.7. Performing Tasks after a Delay with GCD 368
7.8. Performing a Task Only Once with GCD 371
7.9. Grouping Tasks Together with GCD 373
7.10. Constructing Your Own Dispatch Queues with GCD 377
7.11. Running Tasks Synchronously with Operations 380
7.12. Running Tasks Asynchronously with Operations 387
7.13. Creating Dependency Between Operations 393
7.14. Creating Timers 395
7.15. Creating Concurrency with Threads 400
7.16. Invoking Background Methods 406
7.17. Exiting Threads and Timers 407
8. Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
8.1. Enabling Security and Protection for Your Apps 418
8.2. Storing Values in the Keychain 422
8.3. Finding Values in the Keychain 424
8.4. Updating Existing Values in the Keychain 429
8.5. Deleting Exiting Values in the Keychain 432
8.6. Sharing Keychain Data Between Multiple Apps 434
8.7. Writing to and Reading Keychain Data from iCloud 440
8.8. Storing Files Securely in the App Sandbox 443
8.9. Securing Your User Interface 446
9. Core Location and Maps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
9.1. Creating a Map View 450
9.2. Handling the Events of a Map View 452
Table of Contents | v
www.it-ebooks.info
9.3. Pinpointing the Location of a Device 453
9.4. Displaying Pins on a Map View 455
9.5. Displaying Pins with Different Colors on a Map View 459
9.6. Displaying Custom Pins on a Map View 465
9.7. Converting Meaningful Addresses to Longitude and Latitude 468
9.8. Converting Longitude and Latitude to a Meaningful Address 470
9.9. Searching on a Map View 472
9.10. Displaying Directions on the Map 475
10. Implementing Gesture Recognizers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
10.1. Detecting Swipe Gestures 483
10.2. Detecting Rotation Gestures 485
10.3. Detecting Panning and Dragging Gestures 489
10.4. Detecting Long-Press Gestures 491
10.5. Detecting Tap Gestures 495
10.6. Detecting Pinch Gestures 497
11. Networking, JSON, XML, and Sharing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
11.1. Downloading Asynchronously with NSURLConnection 501
11.2. Handling Timeouts in Asynchronous Connections 504
11.3. Downloading Synchronously with NSURLConnection 506
11.4. Modifying a URL Request with NSMutableURLRequest 508
11.5. Sending HTTP GET Requests with NSURLConnection 509
11.6. Sending HTTP POST Requests with NSURLConnection 511
11.7. Sending HTTP DELETE Requests with NSURLConnection 513
11.8. Sending HTTP PUT Requests with NSURLConnection 514
11.9. Serializing Arrays and Dictionaries into JSON 516
11.10. Deserializing JSON into Arrays and Dictionaries 518
11.11. Integrating Social Sharing into Your Apps 521
11.12. Parsing XML with NSXMLParser 525
12. Audio and Video. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
12.1. Playing Audio Files 531
12.2. Handling Interruptions While Playing Audio 534
12.3. Recording Audio 535
12.4. Handling Interruptions While Recording Audio 542
12.5. Playing Audio over Other Active Sounds 543
12.6. Playing Video Files 547
12.7. Capturing Thumbnails from Video Files 551
12.8. Accessing the Music Library 554
13. Address Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
vi | Table of Contents
www.it-ebooks.info
13.1. Requesting Access to the Address Book 564
13.2. Retrieving a Reference to an Address Book 568
13.3. Retrieving All the People in the Address Book 571
13.4. Retrieving Properties of Address Book Entries 573
13.5. Inserting a Person Entry into the Address Book 577
13.6. Inserting a Group Entry into the Address Book 581
13.7. Adding Persons to Groups 584
13.8. Searching the Address Book 587
13.9. Retrieving and Setting a Person’s Address Book Image 592
14. Files and Folder Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
14.1. Finding the Paths of the Most Useful Folders on Disk 603
14.2. Writing to and Reading from Files 605
14.3. Creating Folders on Disk 610
14.4. Enumerating Files and Folders 612
14.5. Deleting Files and Folders 618
14.6. Saving Objects to Files 621
15. Camera and the Photo Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
15.1. Detecting and Probing the Camera 627
15.2. Taking Photos with the Camera 632
15.3. Taking Videos with the Camera 636
15.4. Storing Photos in the Photo Library 639
15.5. Storing Videos in the Photo Library 644
15.6. Retrieving Photos and Videos from the Photo Library 646
15.7. Retrieving Assets from the Assets Library 649
15.8. Editing Videos on an iOS Device 656
16. Multitasking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
16.1. Detecting the Availability of Multitasking 664
16.2. Completing a Long-Running Task in the Background 665
16.3. Adding Background Fetch Capabilities to Your Apps 669
16.4. Playing Audio in the Background 678
16.5. Handling Location Changes in the Background 682
16.6. Saving and Loading the State of Multitasking Apps 684
16.7. Handling Network Connections in the Background 688
16.8. Opting Out of Multitasking 691
17. Notifications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
17.1. Sending Notifications 694
17.2. Listening for and Reacting to Notifications 696
17.3. Listening and Reacting to Keyboard Notifications 700
Table of Contents | vii
www.it-ebooks.info
17.4. Scheduling Local Notifications 707
17.5. Listening for and Reacting to Local Notifications 711
17.6. Handling Local System Notifications 714
17.7. Setting Up Your App for Push Notifications 718
17.8. Delivering Push Notifications to Your App 724
17.9. Reacting to Push Notifications 732
18. Core Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735
18.1. Creating a Core Data Model with Xcode 737
18.2. Generating Class Files for Core Data Entities 741
18.3. Creating and Saving Data Using Core Data 745
18.4. Reading Data from Core Data 747
18.5. Deleting Data from Core Data 750
18.6. Sorting Data in Core Data 752
18.7. Boosting Data Access in Table Views 754
18.8. Implementing Relationships in Core Data 761
18.9. Fetching Data in the Background 768
18.10. Using Custom Data Types in Your Core Data Model 772
19. Dates, Calendars, and Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
19.1. Requesting Permission to Access Calendars 784
19.2. Retrieving Calendar Groups on an iOS Device 790
19.3. Adding Events to Calendars 792
19.4. Accessing the Contents of Calendars 796
19.5. Removing Events from Calendars 799
19.6. Adding Recurring Events to Calendars 803
19.7. Retrieving the Attendees of an Event 808
19.8. Adding Alarms to Calendars 811
19.9. Handling Event Changed Notifications 814
19.10. Presenting Event View Controllers 816
19.11. Presenting Event Edit View Controllers 822
20. Graphics and Animations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 827
20.1. Enumerating and Loading Fonts 833
20.2. Drawing Text 835
20.3. Constructing, Setting, and Using Colors 836
20.4. Drawing Images 841
20.5. Constructing Resizable Images 845
20.6. Drawing Lines 850
20.7. Constructing Paths 858
20.8. Drawing Rectangles 862
20.9. Adding Shadows to Shapes 866
viii | Table of Contents
www.it-ebooks.info
20.10. Drawing Gradients 873
20.11. Moving Shapes Drawn on Graphic Contexts 882
20.12. Scaling Shapes Drawn on Graphic Contexts 886
20.13. Rotating Shapes Drawn on Graphic Contexts 889
20.14. Animating and Moving Views 890
20.15. Animating and Scaling Views 900
20.16. Animating and Rotating Views 901
20.17. Capturing a Screenshot of Your View into an Image 903
21. Core Motion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 907
21.1. Detecting the Availability of an Accelerometer 908
21.2. Detecting the Availability of a Gyroscope 910
21.3. Retrieving Accelerometer Data 911
21.4. Detecting Shakes on an iOS Device 915
21.5. Retrieving Gyroscope Data 916
22. iCloud. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919
22.1. Setting Up Your App for iCloud 920
22.2. Storing and Synchronizing Dictionaries in iCloud 924
22.3. Creating and Managing Folders for Apps in iCloud 929
22.4. Searching for Files and Folders in iCloud 936
22.5. Storing User Documents in iCloud 946
22.6. Managing the State of Documents in iCloud 961
23. Pass Kit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 965
23.1. Creating Pass Kit Certificates 968
23.2. Creating Pass Files 975
23.3. Providing Icons and Images for Passes 984
23.4. Preparing Your Passes for Digital Signature 987
23.5. Signing Passes Digitally 989
23.6. Distributing Passes Using Email 993
23.7. Distributing Passes Using Web Services 995
23.8. Enabling Your iOS Apps to Access Passes on iOS Devices 997
23.9. Interacting with Passbook Programmatically 1003
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007
Table of Contents | ix
www.it-ebooks.info
www.it-ebooks.info
Preface
This edition of the book is not just an update, but a total remake of the previous edition.
iOS 7 changed everything: the look and feel, the way we use our iOS devices, and most
importantly, the way we program for iOS devices. This called for a substantial rewrite
indeed. I have added roughly 50 new recipes to this book, talking about things such as
UIKit dynamics, collection views, the keychain, push notifications, and whatnot. I have
also gone through all the example codes and figures and updated them for iOS 7.
iOS 7 is a huge step forward for this amazing operating system that we all, as program‐
mers and users, have grown to love and enjoy programming for. You must have noticed
how the focus of iOS 7 is on being dynamic: how your UI should adapt to various
movements and motions that can be applied to the device. What I mean by that is Apple
wants developers to really look at the details of their apps and bring real-world physics
and dynamics into them. That’s why Apple introduced UIKit Dynamics to the SDK, and
that is why this book has a whole chapter dedicated to this concept. The more expensive
a high-end device such as the new iPhone becomes, the more demanding the users will
get as well. Nobody blames them, though! They have just bought a fantastic and topof-the-line new iPhone or iPad and they want to see amazing apps running on them,
leveraging all the capabilities that those devices have to offer.
That is why now more than ever developers have to get an in-depth knowledge of the
SDK and what the SDK has to offer to the developers so that we can create better and
faster apps for iOS users. Apple introduced a lot of cool new APIs to the iOS 7 SDK, and
we are going to explore them in this book.
The focus of iOS 7 is dynamics!
Before you read about this book, maybe you’d like to know about my background a bit
and how I can help you through this journey. I will just briefly let you know who I am
and how I got to love iOS. I started out writing Basic code for my Commodore 64 when
I was a kid. I then moved on to buy my own PC and started experimenting with Assembly
code. At first, it was 8-bit Assembly for DOS. I then moved onto writing my own hobby
xi
www.it-ebooks.info
operating system, which was never really released as a commercial product, for 32-bit
Intel x86 CPU architectures.
Among all the programming languages that I have programmed in, Assembly and
Objective-C are the two that have really been different from the others, and I’ve really
liked them. Assembly because of the purity of the language: a command does only one
thing and does that one thing well. I believe that I like Objective-C for the same reason,
and in fact iOS shares the same trait with Assembly and Objective-C. Even though iOS
is an operating system and not a programming language, whatever it does, it does it best
and better than its rivals. From its simplicity to the sheer power that you can harvest
from the software and the hardware combined, using technologies such as GCD, the
bar that iOS has set in terms of ease of use and beauty is unprecedented.
This edition of the book has seen all the recipes inside all chapters completely renewed
for iOS 7. All screenshots have been updated, and many more recipes—such as those
related to security and the keychain, UI dynamics, collection views, push and local
notifications, and many more—have exclusively been written for this edition of the
book. I really have had a fun time writing this edition of the book, and packed as it is
with new features, I hope you’ll enjoy reading it. May it be a valuable addition to your
tech-book library.
Audience
I assume you are comfortable with the iOS development environment and know how
to create an app for the iPhone or iPad. This book does not get novice programmers
started but presents useful ways to get things done for iOS programmers ranging from
novices to experts.
Organization of This Book
In this book, we will discuss frameworks and classes that are available in the iOS 7 SDK.
This book does its best to teach you the latest and the greatest APIs. As you know, some
users of your apps may still be on older versions of iOS, so please consider those users
and choose your APIs wisely, depending on the minimum iOS version that you want to
target with your apps.
Apple has recommended that you write your apps so that they support and run on iOS
6 and iOS 7. This means you need to use the latest SDK as your base SDK (the SDK that
you use to compile your app) and choose iOS 6 as your target, if that’s what your business
requirements dictate. If you are required to write your app to support only iOS 7, then
you are in for a lot of fun, as you can use all the cool APIs that have been introduced in
iOS 7 and discussed in this book.
xii | Preface
www.it-ebooks.info
Here is a concise breakdown of the material each chapter covers:
Chapter 1, Implementing Controllers and Views
Explains how Objective-C classes are structured and how objects can be instanti‐
ated. The chapter talks about properties and delegates and subscripting by keys and
indexes. Even if you are competent in Objective-C, I strongly suggest that you read
this chapter, even if you only skim through it, to understand the basic material that
is used in the rest of the book. In this chapter, we will also explore the common
usage of various UI components, such as alert views, segmented controls, switches,
and labels. We will also talk about customizing these components with the latest
APIs provided in the SDK.
Chapter 2, Creating Dynamic and Interactive User Interfaces
Talks about UIKit Dynamics, the newest addition to the UIKit framework. These
dynamics allow you to add real-life physics and dynamics to your UI components.
This will allow you to create even livelier user interfaces with very small effort on
your side.
Chapter 3, Auto Layout and the Visual Format Language
Explains how you can take advantage of Auto Layout in the iOS SDK in order to
construct your UI in such a way that it can be resized and stretched to pretty much
any screen dimension.
Chapter 4, Constructing and Using Table Views
Shows how you can work with table views to create professional-looking iOS ap‐
plications. Table views are very dynamic in nature, and as a result, programmers
sometimes have difficulty understanding how they should work with them. By
reading this chapter and trying out the example code, you will gain the knowledge
that is required to comfortably work with table views.
Chapter 5, Building Complex Layouts with Collection Views
Collection views have been available to OS X programmers for quite some time
now, and Apple decided to provide the same APIs to iOS programmers in the iOS
SDK. Collection views are very much like table views, but they are much more
configurable and dynamic. Where in table views we have the concept of sections
and rows in each section, collection views bring columns to the equation as well,
so that you can display many items in one row if you want to. In this chapter we
will have a look at all the great user interfaces that you can create using collection
views.
Chapter 6, Storyboards
Demonstrates the process of storyboarding, the new way to define the connections
between different screens in your app. The great thing about storyboarding is that
you don’t have to know anything about iOS programming to get a simple app run‐
ning. This helps product analysts, product owners, or designers who work inde‐
pendently of developers to gain knowledge of the UI components iOS offers and to
Preface | xiii
www.it-ebooks.info