iOS 10 Swift Programming Cookbook Solutions and Examples for iOS Apps Vandad Nahavandipoor iOS 10 Swift Programming Cookbook by Vandad Nahavandipoor Copyright © 2017 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://www.oreilly.com/safari). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Editor: Rachel Roumeliotis Production Editor: Shiny Kalapurakkel Copyeditor: Jasmine Kwityn Proofreader: Rachel Monaghan Indexer: Judy McConville Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Panzer December 2016: First Edition Revision History for the First Edition 2016-12-01: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491966433 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS 10 Swift Programming Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the author have used good faith efforts to ensure that the information and instructions 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 intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-491-96643-3 [LSI] Preface Along with the typical upgrades and shiny new features of every release, iOS 10 offers two major, possibly game-changing opportunities that demonstrate its movement toward integration and enabling extensions. First, it has opened up Siri for developers. This gives us a world of voice interfaces to explore, such as creating fitness applications entirely controlled by Siri, or creating financial applications that allow the receiving and sending of payments from and to others. Apple has also opened up iMessage as a service to us developers, meaning that you can now write applications that allow users to send custom stickers (including animated stickers) to one another. What’s even better is that iMessage has become a lot more interactive, allowing users to react to messages they receive and attaching pre-built stickers to the messages. This book has been updated with a lot of new material for you, and all existing recipes from iOS 9 Swift Programming Cookbook have been brought up to date to use Swift 3 and Xcode 8. Swift 3’s new features and syntax have also been discussed so that you not only get a good idea of what is new in iOS 10 SDK, but also learn about the language you will use to write your apps. I’ve had a lot of fun writing this book and I really hope that you’ll enjoy reading it. Audience I assume that you are comfortable writing iOS apps, at least know your way around Xcode, and can work with the simulator. This book is not for beginners. If you have never programmed in Xcode before for iOS, it will be tough to learn iOS programming only from this book. So I suggest that you complement your skills with other online resources. The intended audience for this book is intermediate and advanced users. I also assume that you have written a little bit of Swift code. In this book, I use Swift 2 and will teach you some of the concepts, but if you don’t know Swift, this is not the right place to start. If you’re just starting out, pick up Apple’s book on Swift programming first; once you’ve read through it and are a bit more comfortable with Swift, come back to this book and I’m sure you’ll learn a lot of new things, even about Swift 2. Organization of This Book Here I’ll explain what each chapter is about so that you’ll get a feeling for what this book is going to teach you: Chapter 1, iMessage Stickers and Apps iOS 10 opens the doors to developers to create sticker pack applications for iMessage. Sticker packs are extensions that you can distribute either as part of your iOS applications or as standalone applications. They allow you to add interactions to messages being sent and received in iMessage conversations. In this chapter, we will discuss different types of these extensions and how you can create interactive sticker pack applications for iMessage. Chapter 2, SiriKit Since its introduction, Siri has been an integral part of iOS and how people interact with the operating system. However, because it was a closed technology, we developers couldn’t integrate our apps into Siri. That’s not the case anymore. Now you can write your own app extensions that integrate into Siri and allow you to interpret various “intents” that come from Siri into your applications. For instance, you can create a financial application that allows the user to send and receive money from various sources, all driven through Siri. In this chapter, you will see how to create one of these extensions and learn the different entry points from Siri into your application. Chapter 3, Measurements and Units This chapter is dedicated to the new series of classes and structures that Apple has provided to developers to convert betweeen various measurements and units. Chapter 4, Core Data Core Data is without a doubt the standard and best way to store large amounts of data, and structure your data object models, in an iOS application. Previous versions of this book included a chapter about Core Data, but that chapter was intentionally removed in the iOS 9 edition, because it had been present in the book since the iOS 6 edition with little alteration. In this edition of the book, I have rewritten this chapter with fresh and new information so that you can enjoy storing data in your iOS apps, knowing you are using the latest APIs. Chapter 5, Swift 3.0, Xcode 8, and Interface Builder In this chapter, we take a look at a lot of new stuff in Swift, Xcode, and Interface Builder (IB), such as the addition of the guard keyword to Swift and conditionally extending types with Swift’s new runtime features. Swift has really matured with Swift 3, and I want to share some of the most important additions with you. Chapter 6, The User Interface This year’s WWDC has put playgrounds under the spotlight and given them some long- needed attention. Playgrounds can now work just like an iOS application, in that they can have a main loop and allow you to continuously change and modify your code while it is running in the background, compiling your changes continuously and displaying the results without you having to press the play button. This chapter looks at these additions to playgrounds as well as other UI components and technologies that might interest you while developing modern iOS apps. Chapter 7, Apple Watch This year, unlike the last, Apple didn’t focus as much on watchOS. However, there are exciting new ways of interacting with watchOS, which we will talk about and discuss in this chapter. Chapter 8, Contacts The contacts APIs will be discussed in this chapter. You’ll learn how to use the contacts framework to add new contacts to the user’s device, remove contacts, edit them, or even allow the user to pick a contact from the list so that you can perform your tasks on it — all without having to fiddle with low-level C APIs. Chapter 9, Extensions The Safari Content Blocker extension allows developers to create apps that get installed as extensions on the user’s Safari browser, and allows us to block various elements of web pages that the user views. For instance, you can now block pictures or various unwanted elements in the websites that you specify in your app, and you can share these content blockers with those who use your app. This chapter is all about these extension points that you can add to your apps. Chapter 10, Web and Search Apps can now provide content to iOS for indexing in the device’s search engine. iOS will then index these contents and allow the user to search for them right within Spotlight on their devices. Your contents can also be indexed globally on Apple’s servers so even those who don’t have your app can see your content on their devices. Intrigued? Read this chapter, then! Chapter 11, Multitasking In iOS, we have the ability to provide Picture in Picture (PiP) to our users. Your app can provide a video player to iOS and allow the user to minimize your whole app into that video player while she works with other apps. It’s really cool, in my opinion! Chapter 12, Maps and Location With the additions to Core Location and MapKit frameworks, you can, for example, display an ETA for transit between two locations or display your custom view inside the annotation of a pin on the map. Chapter 13, UI Testing We will discuss Apple’s UI Testing framework in this chapter. I’ll show you how to write native Swift code to do UI testing. Chapter 14, Core Motion Core Motion is also available on watchOS. In this chapter, you’ll learn some of the new things that you can do with this framework, including reading cadence information from sensors on the device. Chapter 15, Security ATS in iOS forces all requests to go through HTTPS. If you build your project with the latest Xcode and iOS SDK, all your network requests will go through HTTPS by default, protecting your content and possibly breaking a few things if you don’t support HTTPS in your web services. Read this chapter to learn more. Chapter 16, Multimedia iOS 10 adds some new ways for apps to interact with Siri’s voice, and you can read about them in this chapter. Chapter 17, UI Dynamics Last but not least, there are some amazing effects that you can achieve in your user interface with UI Dynamics, including the ability to create turbulence or magnetic fields. In this chapter, we’ll review some examples that show these effects in action.