logo资料库

最新iOS.9.Swift.Programming.Cookbook.pdf

第1页 / 共364页
第2页 / 共364页
第3页 / 共364页
第4页 / 共364页
第5页 / 共364页
第6页 / 共364页
第7页 / 共364页
第8页 / 共364页
资料共364页,剩余部分请下载后查看
Cover
Copyright
Preface
Audience
Organization of This Book
Additional Resources
Acknowledgments
Table of Contents
Chapter 1. Swift 2.0, Xcode 7 and Interface Builder
1.1 Handling Errors in Swift
Problem
Solution
Discussion
See Also
1.2 Specifying Preconditions for Methods
Problem
Solution
Discussion
See Also
1.3 Ensuring the Execution of Code Blocks Before Exiting Methods
Problem
Solution
Discussion
See Also
1.4 Checking for API Availability
Problem
Solution
Discussion
See Also
1.5 Categorizing and Downloading Assets to Get Smaller Binaries
Problem
Solution
Discussion
See Also
1.6 Exporting Device-Specific Binaries
Problem
Solution
Discussion
See Also
1.7 Linking Separate Storyboards Together
Problem
Solution
Discussion
See Also
1.8 Adding Multiple Buttons to the Navigation Bar
Problem
Solution
Discussion
See Also
1.9 Optimizing Your Swift Code
Problem
Solution
Discussion
See Also
1.10 Showing the Header View of Your Swift Classes
Problem
Solution
Discussion
See Also
1.11 Creating Your Own Set Types
Problem
Solution
Discussion
See Also
1.12 Conditionally Extending a Type
Problem
Solution
Discussion
See Also
1.13 Building Equality Functionality Into Your Own Types
Problem
Solution
Discussion
See Also
1.14 Looping Conditionally Through a Collection
Problem
Solution
Discussion
See Also
1.15 Designing Interactive Interface Objects in Playgrounds
Problem
Solution
Discussion
See Also
1.16 Grouping Switch Statement Cases Together
Problem
Solution
Discussion
See Also
1.17 Bundling and Reading Data in Your Apps
Problem
Solution
Discussion
See Also
Chapter 2. Apple Watch
2.1 Downloading Files Onto the Apple Watch
Problem
Solution
Discussion
See Also
2.2 Noticing Changes in Pairing State Between the iOS and Watch Apps
Problem
Solution
Discussion
See Also
2.3 Transferring Small Pieces of Data To and From the Watch
Problem
Solution
Discussion
See Also
2.4 Transferring Dictionaries in Queues To and From the Watch
Problem
Solution
Discussion
See Also
2.5 Transferring Files To and From the Watch
Problem
Solution
Discussion
See Also
2.6 Communicating Interactively Between iOS and watchOS
Problem
Solution
Discussion
See Also
2.7 Setting up Apple Watch for Custom Complications
Problem
Solution
Discussion
See Also
2.8 Constructing Small Complications with Text and Images
Problem
Solution
Discussion
See Also
2.9 Displaying Time Offsets in Complications
Problem
Solution
Discussion
See Also
2.10 Displaying Dates in Complications
Problem
Solution
Discussion
See Also
2.11 Displaying Times in Complications
Problem
Solution
Discussion
See Also
2.12 Displaying Time Intervals in Complications
Problem
Solution
Discussion
See Also
2.13 Recording Audio in Your Watch App
Problem
Solution
Discussion
See Also
2.14 Playing Local and Remote Audio and Video in Your Watch App
Problem
Solution
Discussion
See Also
Chapter 3. The User Interface
3.1 Arranging Your Components Horizontally or Vertically
Problem
Solution
Discussion
See Also
3.2 Customizing Stack Views for Different Screen Sizes
Problem
Solution
Discussion
See Also
3.3 Creating Anchored Constraints in Code
Problem
Solution
Discussion
See Also
3.4 Allowing Users to Enter Text in Response to Local and Remote Notifications
Problem
Solution
Discussion
See Also
3.5 Dealing with Stacked Views in Code
Problem
Solution
Discussion
See Also
3.6 Showing Web Content in Safari View Controller
Problem
Solution
Discussion
See Also
3.7 Laying Out Text-Based Content on Your Views
Problem
Solution
Discussion
See Also
3.8 Improving Touch Rates for Smoother UI Interactions
Problem
Solution
Discussion
See Also
3.9 Supporting Right-to-Left Languages
Problem
Solution
Discussion
See Also
3.10 Associating Keyboard Shortcuts with View Controllers
Problem
Solution
Discussion
See Also
3.11 Recording the Screen and Sharing the Video
Problem
Solution
Discussion
See Also
Chapter 4. Contacts
4.1 Creating Contacts
Problem
Solution
Discussion
See Also
4.2 Searching for Contacts
Problem
Solution
Discussion
See Also
4.3 Updating Contacts
Problem
Solution
Discussion
See Also
4.4 Deleting Contacts
Problem
Solution
Discussion
See Also
4.5 Formatting Contact Data
Problem
Solution
Discussion
See Also
4.6 Picking Contacts with the Prebuilt System UI
Problem
Solution
Discussion
See Also
4.7 Creating Contacts with Prebuilt System UI
Problem
Solution
Discussion
See Also
4.8 Displaying Contacts with Prebuilt System UI
Problem
Solution
Discussion
See Also
Chapter 5. Extensions
5.1 Creating Safari Content Blockers
Problem
Solution
Discussion
See Also
5.2 Creating Shared Links for Safari
Problem
Solution
Discussion
See Also
5.3 Maintaining Your App’s Indexed Content
Problem
Solution
Discussion
See Also
Chapter 6. Web and Search
6.1 Making Your App’s Content Searchable
Problem
Solution
Discussion
See Also
6.2 Making User Activities Searchable
Problem
Solution
Discussion
See Also
6.3 Deleting Your App’s Searchable content
Problem
Solution
Discussion
See Also
Chapter 7. Multitasking
7.1 Adding Picture in Picture Playback Functionality
Problem
Solution
Discussion
See Also
7.2 Handling Low Power Mode and Providing Alternatives
Problem
Solution
Discussion
See Also
Chapter 8. Maps and Location
8.1 Requesting the User’s Location a Single Time
Problem
Solution
Discussion
See Also
8.2 Requesting the User’s Location in Background
Problem
Solution
Discussion
See Also
8.3 Customizing the Tint Color of Pins on the Map
Problem
Solution
Discussion
See Also
8.4 Providing Detailed Pin Information with Custom Views
Problem
Solution
Discussion
See Also
8.5 Displaying Traffic, Scale and Compass Indicators on the Map
Problem
Solution
Discussion
See Also
8.6 Providing an ETA for Transit Transport Type
Problem
Solution
Discussion
See Also
8.7 Launching the iOS Maps App in Transit Mode
Problem
Solution
Discussion
See Also
8.8 Showing Maps in Flyover Mode
Problem
Solution
Discussion
See Also
Chapter 9. UI Testing
9.1 Preparing Your Project for UI Testing
Problem
Solution
Discussion
See Also
9.2 Automating UI Test Scripts
Problem
Solution
Discussion
See Also
9.3 Testing Text Fields, Buttons, and Labels
Problem
Solution
Discussion
See Also
9.4 Finding UI Components
Problem
Solution
Discussion
See Also
9.5 Long Pressing on UI Elements
Problem
Solution
Discussion
See Also
9.6 Typing Inside Text Fields
Problem
Solution
Discussion
See Also
9.7 Swiping on UI Elements
Problem
Solution
Discussion
See Also
9.8 Tapping on UI Elements
Problem
Solution
Discussion
See Also
Chapter 10. Core Motion
10.1 Querying Pace and Cadence Information
Problem
Solution
Discussion
See Also
10.2 Recording and Reading Accelerometer Data
Problem
Solution
Discussion
See Also
Chapter 11. Security
11.1 Protecting Your Network Connections with ATS
Problem
Solution
Discussion
See Also
11.2 Binding Keychain Items to Passcode and Touch ID
Problem
Solution
Discussion
See Also
11.3 Opening URLs Safely
Problem
Solution
Discussion
See Also
11.4 Authenticating the User with Touch ID and Timeout
Problem
Solution
Discussion
See Also
Chapter 12. Multimedia
12.1 Reading Out Text with the Default Siri Alex Voice
Problem
Solution
Discussion
See Also
12.2 Downloading and Preparing Remote Media for Playback
Problem
Solution
Discussion
See Also
12.3 Enabling Spoken Audio Sessions
Problem
Solution
Discussion
See Also
Chapter 13. UI Dynamics
13.1 Adding a Radial Gravity Field to Your UI
Problem
Solution
Discussion
See Also
13.2 Creating a Linear Gravity Field on Your UI
Problem
Solution
Discussion
See Also
13.3 Creating Turbulence Effects with Animations
Problem
Solution
Discussion
See Also
13.4 Adding Animated Noise Effects to Your UI
Problem
Solution
Discussion
See Also
13.5 Creating a Magnetic Effect Between UI Components
Problem
Solution
Discussion
See Also
13.6 Designing a Velocity Field on Your UI
Problem
Solution
Discussion
See Also
13.7 Handling Non-Rectangular Views
Problem
Solution
Discussion
See Also
Index
About the Author(s)
a ers S v n d X c o C o wift 2 d e 7 E a r l y R e l e a s e R A W & U N E D I T E D iOS 9 Swift Programming Cookbook SOLUTIONS & EXAMPLES FOR IOS APPS Vandad Nahavandipoor
iOS 9 Swift Programming Cookbook Vandad Nahavandipoor
iOS 9 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 Copyeditor: FILL IN COPYEDITOR Proofreader: FILL IN PROOFREADER Indexer: FILL IN INDEXER Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest November 2014: First Edition Revision History for the First Edition 2015-09-30: First Early Release See http://oreilly.com/catalog/errata.csp?isbn=9781491936696 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS 8 Swift Programming Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the author(s) have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author(s) disclaim all responsibil‐ ity 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-93669-6 [FILL IN]
Preface When I started writing this edition of this book (which has been in the field and regu‐ larly updated since iOS version 4), I thought to myself: what I should do to really overhaul it and make it even more exciting than the previous editions? The answer was to rewrite the whole book--every single word from scratch. Up to and including the iOS 8 Swift Programming Cookbook (where I made the big switch from Objective-C to Swift) was to base every edition on the previous edition. I would go through all the examples from the previous edition to remove the ones that were irrelevant for the new edition or just expendable because they were very simple and basic. I’d then update the remaining examples to make sure they work great with the new iOS version. Then I would also write new content for the new version of iOS. However, after 5 editions, I noticed that many recipes were not really useful anymore and had stayed almost the same since the beginning. So how could I solve this issue? The solution was to not do this any longer. I had to write all new content, and that’s what I did for this book. The amount of work that went into this writing this book was tremendous, on my side, and on O’Reilly’s side. I have had to think long and hard about every new recipe, writing all the example code anew and ensuring it works with the latest production tools from Apple. You will learn a lot about Swift 2 and iOS 9 SDK in this book. And yes, there is a great deal of watchOS material in this book. The chapter dedicated to watchOS has more content in it than any other chapter. The reason behind that decision was that watchOS was the main focus for this year’s WWDC and that Apple has paid more attention to watchOS in iOS 9 SDK than to other frameworks or tools that they have published this year. I hope you’ll enjoy writing watchOS apps as much as I do. One last thing. Since Swift changes a lot and is constantly updated, please always check the GitHub repo for this book to get the most up-to-date code. I have ensured that all code compiles and works fine with Xcode 7 and the iOS 9 SDK, but if for some reason you are on a beta Xcode that is newer than the production version of iii
Xcode 7 that Apple has released, do ensure that you have the latest code by checking out this book’s GitHub repo. Have fun and I hope you’ll enjoy reading this book. 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 program‐ ming only from this book. So I suggest that you compliment your skills with other online resources. The best market 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. Please pick up Apple’s book on Swift programming first; try with that and once you are a bit 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: Swift 2.0, Xcode 7 and Interface Builder In this chapter, we go through a lot of new stuff in Swift, Xcode, and Interface Builder, such as the addition of the guard keyword to Swift and conditionally extend‐ ing types with Swift’s new runtime features. Swift has really matured with Swift 2, and I want to share some of the most important additions with you. Apple Watch This year’s WWDC star, without a doubt, is watchOS 2 with all its additions. Now apps can run natively on the watchOS without having to talk to the iOS counterpart app, and this is great for us. More work, more things to do, more fun. We will talk about complications, transferring files between iOS and watchOS 2 apps, download‐ ing files right on the watch, recording audio, and playing multimedia on your watch. The User Interface Even though additions to UIKit were not talked about as extensively as watchOS 2 in this year’s WWDC, there are still tons of new features that we can discuss, including anchored constraints, stack views and the new Safari view controller. Contacts The all-new contacts APIs will be discussed in this chapter. The frameworks on which this chapter is based are both completely new to iOS 9. With the APIs in these frameworks, you’ll learn how to add new contacts to the user’s device, remove con‐ iv | Preface
tacts, edit them, or even allow the user to pick a contact from the list so that you can perform your tasks on it. Extensions Safari Content Blockers shocked a lot of developers during this year’s WWDC. This allows us 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 new extension points that you can add to your apps. Web and Search Apps can now provide content to iOS. iOS will then index these contents and allow the user to search for these contents right within Spotlight on their devices. Your con‐ tents 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. Intriguied? Read this chapter, then! Multitasking We now have Picture in Picture (PiP) in iOS. 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. Maps and Location With the additions to Core Location and MapKit frameworks, you can now, for example, display an ETA for transit between two locations or display your custom view inside the annotation of a pin on the map. UI Testing One of the stars of this year’s WWDC is Apple’s new UI Testing framework. We can now write native Swift code to do our UI testing and I’m going to show you how, in this chapter. Core Motion Core Motion is now also available on watchOS 2 and 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. Security ATS is a welcome addition in iOS that forces all requests to go through HTTPS. If you build your project with Xcode 7 and iOS 9 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. Multimedia We have some new additions to how apps can interact with Siri and you can read about them in this chapter. Preface | v
UI Dynamics Last but not least, there are some amazing effects that you can achieve in your user interface with the new additions to UI Dynamics, including the ability to create tur‐ bulence or magnetic fields. In this chapter, I’ll show you these additions with exam‐ ples. Additional Resources This book is not for beginners, so I assume you have already gotten a grip on Swift and can do basic things with it. Please read Apple’s documentation on Swift by doing a quick web search. You can either read it on your browser, as a PDF, or you can read it in iBooks. Also please check this book’s GitHub repository in order to get the most up-to-date code, as I update the code to ensure it works with the latest Swift and Xcode versions. Acknowledgments Thank you to: Sara, Julian and Molly For continuously supporting and encouraging me. Rachel Roumeliotis For always having trust in me and knowing that I stick to my words when I promise to write a whole new book in a short period of time with quality material. Your trust means a lot to me and I hope this book will make you proud, as much as it made me. Andy Oram The editor that anybody would dream about, Andy has been by my side editing this book non-stop since I started. His relentless efforts have allowed me to relax while he craftfully works his way through the book, making it even more understandable for the readers. I would not be able to write this book without Andy’s help. Niklas Saers For his detailed technical review of this book. vi | Preface
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii 1. Swift 2.0, Xcode 7 and Interface Builder. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.1 Handling Errors in Swift 11 1.2 Specifying Preconditions for Methods 13 1.3 Ensuring the Execution of Code Blocks Before Exiting Methods 15 1.4 Checking for API Availability 16 1.5 Categorizing and Downloading Assets to Get Smaller Binaries 18 1.6 Exporting Device-Specific Binaries 21 1.7 Linking Separate Storyboards Together 22 1.8 Adding Multiple Buttons to the Navigation Bar 24 1.9 Optimizing Your Swift Code 25 1.10 Showing the Header View of Your Swift Classes 28 1.11 Creating Your Own Set Types 30 1.12 Conditionally Extending a Type 31 1.13 Building Equality Functionality Into Your Own Types 33 1.14 Looping Conditionally Through a Collection 35 1.15 Designing Interactive Interface Objects in Playgrounds 37 1.16 Grouping Switch Statement Cases Together 39 1.17 Bundling and Reading Data in Your Apps 40 2. Apple Watch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 2.1 Downloading Files Onto the Apple Watch 50 2.2 Noticing Changes in Pairing State Between the iOS and Watch Apps 56 2.3 Transferring Small Pieces of Data To and From the Watch 60 2.4 Transferring Dictionaries in Queues To and From the Watch 70 2.5 Transferring Files To and From the Watch 75 2.6 Communicating Interactively Between iOS and watchOS 80 vii
分享到:
收藏