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 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 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 Swift Programming Cookbook iOS 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 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 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 Swift Programming Cookbook iOS Swift Programming Cookbook SOLUTIONS & EXAMPLES FOR IOS APPS CAN $62.99 ISBN: 978-1-491-90869-3 Vandad Nahavandipoor www.it-ebooks.info iOS Swift Programming Cookbook Vandad Nahavandipoor www.it-ebooks.info iOS 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 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 The Basics 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 12 17 21 27 31 37 41 46 49 53 57 63 68 70 75 83 88 91 94 97 99 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 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 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 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 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 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 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 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 ... iOS devices Xc iOS Swift Programming Cookbook iOS Swift Programming Cookbook SOLUTIONS & EXAMPLES FOR IOS APPS CAN $62.99 ISBN: 9 78- 1-491-9 086 9-3 Vandad Nahavandipoor www.it-ebooks.info iOS Swift. .. Synchronizing Dictionaries in iCloud 21 .8 Creating and Managing Files and Folders in iCloud 21.9 Searching for Files and Folders in iCloud 80 7 81 2 82 0 82 6 83 1 83 9 84 6 85 1 85 5 Index ... right away coding with new “ From iOS features to tackling iOS Swift Programming Cookbook Entirely rewritten for Apple’s Swift programming language, this updated cookbook helps you overcome the