46,44 €
Become a professional iOS developer with the most in-depth and advanced guide to Swift, Xcode 10, ARKit, and Core ML
Key Features
Book Description
The iOS development environment has significantly matured, and with Apple users spending more money in the App Store, there are plenty of development opportunities for professional iOS developers. However, the journey to mastering iOS development and the new features of iOS 12 is not straightforward. This book will help you make that transition smoothly and easily. With the help of Swift 4.2, you'll not only learn how to program for iOS 12, but also how to write efficient, readable, and maintainable Swift code that maintains industry best practices.
Mastering iOS 12 Programming will help you build real-world applications and reflect the real-world development flow. You will also find a mix of thorough background information and practical examples, teaching you how to start implementing your newly gained knowledge.
By the end of this book, you will have got to grips with building iOS applications that harness advanced techniques and make best use of the latest and greatest features available in iOS 12.
What you will learn
Who this book is for
If you're a developer with some experience in iOS programming and want to enhance your skills by unlocking the full potential of the latest iOS version with Swift to build great applications, this book is for you.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 943
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Amarabha BanerjeeAcquisition Editor: Trusha ShriyanContent Development Editor: Onkar WaniTechnical Editor: Ralph RosarioCopy Editor: Safis EditingProject Coordinator: Sheejal ShahProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Alishon MendonsaProduction Coordinator: Aparna Bhagat
First published: December 2016 Second edition: October 2017 Third edition: October 2018
Production reference: 1311018
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78913-320-2
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Donny Walsis a passionate, curious, iOS developer from The Netherlands. With several years of experience in building apps and sharing knowledge under his belt, Donny is a respected member of the iOS development community. Donny enjoys delivering talks on smaller and larger scales to share his knowledge and experiences with his peers.
In addition to sharing knowledge, Donny loves learning more about iOS, Apple's frameworks and development in general. This eagerness to learn has made him into a versatile iOS developer with knowledge of a significant number of Apple's frameworks and tools. During WWDC you will often find Donny binge-watching the talks that Apple engineers deliver to introduce new features and frameworks.
Cecil Costa, also known as Eduardo Campos in Latin countries, is a Euro-Brazilian freelance developer. He has been giving onsite courses for companies such as Ericsson, Roche, TVE (a Spanish TV channel), and others. He has also worked for different companies, including IBM, Qualcomm, Spanish Lottery, and Dia. Heis also the author of Swift Cookbook, Swift 2 Blueprints, Reactive Programming with Swift, and a video course called Building iOS 10 Applications with Swift, by Packt Publishing.
Nikola Brežnjak is an engineer at heart and a jack of all trades kind of guy. Currently, he's the director of mobile engineering at Teltech and is responsible for the management, mentoring and coaching of mobile app developers. He loves his job!
He wrote books on the Ionic framework and the MEAN stack and was a technical reviewer for few of Packt's books.
He likes to help out on StackOverflow where he's a top contributor. He records a podcast called DevThink with his friend Shawn Milochik and runs a local meetup called MeCoDe.
Shaun Rowe is a software engineer with over 20 years of professional experience. He wrote his first line of code at the age of 11 and began his career at the height of the dot com boom. He has been developing for Apple platforms for over 8 years, as soon as Swift was officially supported by XCode he became an early adopter. During his 20 years in the industry he has worked in many fields and many disciplines, gaining knowledge and experience in all aspects of software development, from the web to mobile. He ran a successful mobile development agency for a number of years before moving to Amsterdam for a new and exciting opportunity at the end of 2017.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Mastering iOS 12 Programming Third Edition
Dedication
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
UITableView Touch-up
Setting up the user interface
Fetching a user's contacts
Creating a custom UITableViewCell to show contacts
Designing a table-view cell
Creating the table-view cell subclass
Displaying the list of contacts
Protocols and delegation
Conforming to the UITableViewDataSource and UITableViewDelegate protocols
Under-the-hood performance of UITableView
Improving performance with prefetching
UITableViewDelegate and interactions
Responding to cell-selection
Implementing cell-deletion
Allowing the user to reorder cells
Summary
Questions
Further reading
A Better Layout with UICollectionView
Converting from a table view to a collection view
Creating and implementing a custom collection view cell
Understanding UICollectionViewFlowLayout and its delegate
Creating a custom UICollectionViewLayout
Pre-calculating the layout
Implementing collectionViewContentSize
Implementing layoutAttributesForElements(in:)
Implementing layoutAttributesForItem(at:)
Implementing shouldInvalidateLayout(forBoundsChange:)
Assigning a custom layout to your collection view
Final words on the custom layout
UICollectionView performance
Implementing user interactions for the collection view
Enabling cell selection for your collection view
Allowing users to delete cells
Reordering cells in a collection view
Refactoring the long-press handler
Implementing the reordering method calls
Implementing the data source methods
Adding the edit button
Summary
Questions
Further reading
Creating a Detail Page
Building universal applications
Implementing navigation with segues
Creating adaptive layouts with Auto Layout
Auto Layout with Interface Builder
Implementing a scroll view with Auto Layout
Laying out the image and name label
Adjusting the image and label for large screens
Laying out the bottom section
Adjusting the bottom section for small screens
Using Auto Layout in code
Implementing the compact size layout
Implementing the regular size layout
Improving layouts with UIStackView
Containing labels in a stack view
Passing data between view controllers
Updating the data loading and model
Passing the model to the details page
Implementing the new outlets and displaying data
Enhancing the user experience with 3D Touch
Summary
Questions
Further reading
Immersing Your Users with Animation
Refactoring existing animations with UIViewPropertyAnimator
Understanding and controlling animation progress
Adding vibrancy to animations
Adding dynamism with UIKit Dynamics
Customizing view-controller transitions
Implementing a custom modal presentation transition
Making an interactive dismissal transition
Implementing a custom UINavigationController transition
Summary
Questions
Further reading
Understanding the Swift Type System
Knowing what types are available
Reference types
Value types
Understanding structs
Understanding enums
Understanding differences in types
Comparing value types to reference types
Differences in usage
Differences in memory allocation
Deciding which type you should use
When to use a reference type?
When to use a value type?
Summary
Questions
Further reading
Writing Flexible Code with Protocols and Generics
Defining your own protocols
Checking for traits instead of types
Extending your protocols with default behavior
Improving your protocols with associated types
Adding flexibility with generics
Summary
Questions
Further reading
Improving the Application Structure
Properly separating concerns
Extracting the contact-fetching code
Extracting the bounce animation
Adding protocols for clarity
Defining the ViewEffectAnimatorType protocol
Defining a contact-displayable protocol
Summary
Questions
Further reading
Adding Core Data to Your App
Understanding the Core Data Stack
Adding Core Data to an existing application
Creating a Core Data model
Creating the models
Defining relationships
Using your entities
Reading and writing data in a Core Data database
Understanding data persistence
Persisting your models
Refactoring the persistence code
Reading data with a simple fetch request
Filtering data with predicates
Reacting to database changes
Implementing NSFetchedResultsController
Understanding the use of multiple instances of NSManagedObjectContext
Summary
Questions
Further reading
Fetching and Displaying Data from the Network
Fetching data from the web
Understanding URLSession basics
Working with JSON in Swift
Updating Core Data objects with fetched data
Implementing the fetch logic
Updating a movie with a popularity rating
Visualizing multiple threads
Wrapping the feature up
Adding the rating to the movie cell
Understanding App Transport Security
Observing changes to movie ratings
Summary
Questions
Further reading
Being Proactive with Background Fetch
Understanding how background fetch works
Looking at background fetch from a distance
Looking at background fetch in more depth
Implementing the prerequisites for background fetch
Adding the background fetch capability
Asking iOS to wake your app
Updating movies in the background
Updating the data model
Refactoring the existing code
Updating movies in the background
Preparing the helper struct
Updating the movies
Summary
Test your knowledge
Further reading
Syncing Data with CloudKit
Getting familiar with CloudKit
Adding CloudKit to your project
Exploring the CloudKit dashboard
Understanding your CloudKit database
Exploring the rest of your container
Storing and retrieving data with CloudKit
Communicating with CloudKit for the first time
Listening for changes in the database
Retrieving changes from CloudKit
Configuring your AppDelegate
Storing data in CloudKit
Combining CloudKit and Core Data
Preparing the Core Data models for CloudKit
Importing CloudKit data
Sending Core Data models to CloudKit
Summary
Questions
Further reading
Using Augmented Reality
Understanding ARKit
Understanding how ARKit renders content
Understanding how ARKit tracks the physical environment
Using ARKit Quicklook
Implementing the ARKit Quicklook view controller
Exploring SpriteKit
Creating a SpriteKit scene
Exploring SceneKit
Creating a basic SceneKit scene
Implementing an Augmented Reality gallery
Adding image tracking
Preparing images for tracking
Building the image-tracking experience
Placing your own content in 3D space
Summary
Questions
Further reading
Improving Apps With Location Services
Requesting a user's location
Asking for permission to access location data
Obtaining a user's location
Subscribing to location changes
Setting up geofences
Summary
Questions
Further reading
Making Smarter Apps with CoreML
Understanding machine learning and CoreML
Understanding what machine learning is
Understanding CoreML
Obtaining CoreML models
Using a CoreML model
Combining CoreML and computer vision
Understanding the Vision framework
Implementing an image classifier
Training your own models with CreateML
Training a natural language model
Training a Vision model
Summary
Questions
Further reading
Tracking Activity Using HealthKit
Understanding HealthKit
Requesting access to the HealthKit Store
Storing and retrieving data with HealthKit
Implementing a workout app
Summary
Questions
Further reading
Streamlining Experiences with Siri
Understanding intents
Implementing an intents extension
Understanding app extensions
Configuring your extension
Adding vocabularies to your app
Adding vocabularies through a .plist file
Teaching Siri new vocabularies at runtime
Handling intents in your extension
Resolving the user's input
Confirming the intent status
Performing the desired action
Adding a custom UI to Siri
Implementing Siri Shortcuts
Implementing shortcuts through NSUserActivity
Donating shortcuts with INinteractions
Summary
Questions
Further reading
Using Media in Your App
Playing audio and video
Creating a simple video player
Creating an audio player
Implementing basic audio controls
Implementing the time scrubber
Displaying song metadata
Playing media in the background
Recording video and taking pictures
Taking and storing a picture
Recording and storing video
Manipulating photos with Core Image
Summary
Questions
Further reading
Implementing Rich Notifications
Gaining a deep understanding of notifications
Scheduling and handling notifications
Registering for notifications
Creating notification contents
Creating push notifications
Creating local notifications
Scheduling your notification
Scheduling a timed notification
Scheduling a calendar-based notification
Scheduling a location-based notification
Handling notifications
Handling notifications in your app
Managing pending and delivered notifications
Adding actions to notifications
Implementing grouped notifications
Grouping notifications based on thread identifiers
Providing a custom summary message for your notification group
Implementing notification extensions
Adding a service extension to your app
Adding a content extension to your app
Summary
Questions
Further reading
Instant Information with a Today Extension
Understanding the anatomy of a Today Extension
Finding Today Extensions in iOS
Understanding Today Extensions
Adding a Today Extension to your app
Summary
Questions
Further reading
Exchanging Data With Drag And Drop
Understanding the drag and drop experience
Understanding UIDragInteractionDelegate
Understanding UIDropInteractionDelegate
Implementing a basic drag and drop functionality
Adding drag and drop to a plain UIView
Adding drag and drop to a UICollectionView
Customizing the drag and drop experience
Summary
Questions
Further reading
Improved Discoverability with Spotlight and Universal Links
Understanding Spotlight search
Adding your app contents to the Spotlight index
Indexing your app through user activity
Indexing with CSSearchableItem
Containing information in CSSearchableItemAttributeSet
Adding CSSearchableItem instances to the search index
Safely combining indexing methods
Handling searchable item selection
Understanding Spotlight best practices and ratings
Adding metadata to your web links
Registering as an indexing delegate
Increasing your app's visibility with Universal Links
Preparing your server for Universal Links
Handling Universal Links in your app
Summary
Questions
Further reading
Extending iMessage
Understanding iMessage apps
Creating an iMessage sticker pack
Optimizing assets for your stickers
Creating a custom sticker app
Implementing custom, interactive iMessage apps
Understanding the iMessage app life cycle
Implementing the custom compact view
Implementing the expanded view
Understanding sessions, messages, and conversations
Composing a message
Sending a message
Summary
Questions
Further reading
Ensuring App Quality with Tests
Testing logic with XCTest
Understanding what it means to test code
Determining which tests to write
Choosing the correct test type
Unit tests
Integration tests
Isolating tests
Arrange
Act
Assert
Setting up a test suite with XCTest
Optimizing code for testability
Introducing the question loader
Mocking API responses
Using models for consistency
Gaining insights through code coverage
Testing the user interface with XCUITest
Making your app accessible to your tests
Recording UI tests
Passing launch arguments to your app
Making sure the UI updates as expected
Summary
Questions
Further reading
Discovering Bottlenecks with Instruments
Exploring the Instruments suite
Discovering slow code
Closing memory leaks
Understanding what a memory leak is
Preventing objects from using infinite memory
Avoiding reference cycles
Discovering memory leaks
Creating your own Instrument
Adding signpost logging to your app
Building an Instruments Package
Summary
Questions
Further reading
Offloading Tasks with Operations and GCD
Writing asynchronous code
Understanding threads
Using dispatch queues in your application
Creating reusable tasks with Operations
Using Operations in your apps
Summary
Questions
Further reading
Submitting Your App to the App Store
Adding your application to App Store Connect
Packaging and uploading your app for beta testing
Preparing your app for launch
Summary
Questions
Further reading
Answers
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6 
Chapter 7 
Chapter 8 
Chapter 9
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Chapter 14
Chapter 15
Chapter 16
Chapter 17
Chapter 18 
Chapter 19
Chapter 20
Chapter 21
Chapter 22
Chapter 23
Chapter 24
Chapter 25 
Chapter 26 
Other Books You May Enjoy
Leave a review - let other readers know what you think
Mastering iOS 12 is the third book in the Mastering iOS series that started in 2016 when iOS 10 was released. Since the release of the first version, this book has grown in size to make sure all of the new and interesting bits of are iOS covered and to teach you how to make sure your iOS applications meet Apple's latest standards. You will learn everything you need to know to build great applications that are packed with great features.
This book follows a learn-by-doing style of teaching. Every newly introduced topic in every chapter is accompanied by a sample application that shows you how to put the new theory you read into practice. This means that this book is a very practical guide to becoming an iOS master. In addition to teaching you a lot of Apple's new and existing frameworks, a lot of focus is placed on Apple's own documentation. Since not every single iOS framework can be covered in one book, it is crucial that you train yourself in scanning and understanding Apple's documentation.
It doesn't matter whether you haven't managed to build an app before, or if you're an experienced iOS developer. This book will help you become a better iOS developer, and it will teach you everything new that iOS 12 has to offer. You will step beyond the basics and you will learn everything you need to know to build high-quality iOS applications.
This book is for developers who have some experience with iOS programming but want to take their skills to the next level by unlocking the full potential of the latest version of iOS with Swift to build impressive applications. It is assumed that you have some basic knowledge of iOS development throughout the book.
Chapter 1, UITableView Touch-up, covers UITableView, which is the core of many iOS applications. Most developers that attempt to learn iOS will start by implementing a table view. This chapter is intended to provide a warm-up for the next chapters while also providing in-depth information about UITableView and its internals.
Chapter 2, A Better Layout with UICollectionView, explores UITableView's super-powered sibling, UICollectionView. This chapter covers implementing a collection view and writing a custom layout object for it.
Chapter 3, Creating a Detail Page, explains that when you build apps, you'll need to make them work on many different screen sizes. This chapter will show you how to use AutoLayout to create beautiful, adaptive layouts.
Chapter 4, Immersing Your Users with Animation, shows how the best apps set themselves apart with beautiful and subtle animations. In this chapter, you will learn the best animation techniques, and to top it off, you'll learn how to create custom transitions between view controllers.
Chapter 5, Understanding the Swift Type System, focuses on the different data types Swift uses, how they relate to each other, and how to decide what type is best for certain use cases.
Chapter 6, Writing Flexible Code with Protocols and Generics, moves on from learning about the type system's basic concrete types; it's also important to learn about abstractions that make your code more flexible, robust, and future-proof. This chapter will show you how you can improve your Swift code with the right abstractions and principles.
Chapter 7, Improving Application Structure, teaches you how to apply the lessons learned from the previous two chapters to improve an app you've already worked on.
Chapter 8, Adding Core Data to Your App, explains that many apps need to store data in a database. This chapter introduces Apple's Core Data framework as a way to include a database for user data in your app.
Chapter 9, Fetching and Displaying Data from the Network, shows you how you can access data and resources over a network connection and display the results to the user.
Chapter 10, Being Proactive with Background Fetch, explains that iOS allows apps to refresh and load data in the background. You will learn how to implement Background Fetch and you will briefly be introduced to Dispatch Groups.
Chapter 11, Syncing Data with CloudKit, covers how to store data in the cloud with CloudKit. It also covers a scenario where CloudKit is used as online storage, while Core Data is used to persist data locally.
Chapter 12, Using Augmented Reality, demonstrates how you can use Apple's groundbreaking ARKit framework to build an augmented reality experience.
Chapter 13, Improving Apps with Location Services, covers several ways that apps can implement location tracking to enhance and improve a user’s experience.
Chapter 14, Making Smarter Apps with CoreML, teaches everything you should know about the CoreML framework. Readers will implement a machine learning model that recognizes dominant objects in a scene. This chapter also covers CreateML to augment existing models with more specific training data.
Chapter 15, Tracking Activity Using HealthKit, explains how to access a user's health information and how you can implement an app that tracks a user's workouts and stores them in the Health app.
Chapter 16, Streamlining Experiences with Siri, shows you how to integrate the SiriKit APIs in your own applications. This enables you to integrate your app deeply into the iOS platform. It also covers the new Siri shortcuts that allow users to quickly perform actions in certain apps.
Chapter 17,Using Media in Your App, explains how to play back audio and video, take photos, and apply interesting filters to images that users take with your app.
Chapter 18, Implementing Rich Notifications, is a walk-through of everything you need to know about providing a great notification experience for your users. It covers both the UI extension and the content extension.
Chapter 19, Instant Information with a Today Extension, shows that developers can add widgets to the Notification Center to disclose quick information to users; this chapter will teach you how.
Chapter 20, Exchanging Data with Drag and Drop, takes you through how to augment an app to allow users to drag contents from your app to other apps and vice versa.
Chapter 21, Improved Discoverability with Spotlight and Universal Links, explores how you can make an iOS index for your app's contents to make it available through the powerful Spotlight search index.
Chapter 22, Extending iMessage, shows how to build a simple sticker pack and app for iMessage.
Chapter 23, Ensuring App Quality with Tests, focuses on testing, which is an often-overlooked aspect of developing an app. You will learn how to set up tests for your application.
Chapter 24, Discovering Bottlenecks with Instruments, explains how to profile your app's performance with instruments. You also learn how to implement and use your own instrument tools.
Chapter 25, Offloading Tasks with Operations and GCD, covers apps that perform increasingly complex tasks. You will learn how to ensure that complex or slow tasks don't freeze your user interface.
Chapter 26, Submitting Your App to the App Store, explains how to distribute your app to beta testers through TestFlight and how to submit your app for review in order to publish it to the App Store.
All sample code in this book was written in Swift 4.2 with Xcode 10.0 on a Mac running macOS Mojave. To follow along with all the examples in this book you must have at least Xcode 10.0 installed on your machine. It is recommended that you also have at least macOS Mojave installed on your Mac because not all code samples are compatible with older versions of macOS.
This book assumes that you are somewhat familiar with Swift and iOS development. If you have no experience with Swift at all, it is recommended that you skim through Apple's Swift manual and go over the basics of iOS development. You don't have to be an expert on iOS development yet, but a solid foundation won't hurt you since the pacing of the book is aimed at somewhat experienced developers.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-iOS-12-Programming-Third-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789133202_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
There's a good chance that you have built a simple app before, or maybe you have tried but didn't quite succeed. If this is the case, it is likely that you have used UITableView or UITableViewController. UITableView is a core component of many iOS applications. If an app shows a list of things, it was likely built using UITableView. BecauseUITableViewis such an essential component on iOS, I want to make sure that we cover it right away in this book. It doesn't matter whether you have looked atUITableViewbefore. This chapter will ensure that you are up to speed with the ins and outs of UITableView and understand how Apple has made sure that every table view scrolls with a smooth speed of 60 frames per second, which we all strive for when developing apps.
In addition to covering the basics of UITableView, such as how it uses delegation to obtain information about the contents it should display, you'll also learn the basics about accessing a user's data, in this case, their contacts. The application that you will end up building displays a list of the user's contacts in a table view.
Every UITableView uses cells to render each item it displays. In this chapter, you will create your own UITableViewCell that uses Auto Layout. Auto Layout is a layout technique that is used throughout this book due to its essential part of every iOS developer's toolkit. If you haven't used Auto Layout before, or if you haven't heard of it, that's OK. This chapter starts with the basics, and your knowledge will expand as you go through this book.
In summary, this chapter covers:
Configuring and displaying
UITableView
Fetching a user's contacts through
Contacts.framework
The delegate and data source of
UITableView
Creating a custom
UITableViewCell
UITableView
performance characteristics
Every time you start a new project in Xcode, you have the option to pick a template for your application. Every template contains a small amount of code to get you started. Sometimes, a basic layout will even be set up for you. Throughout this book, you should default to using the Single View Application template. Don't be fooled by its name; you can add as many views to your app as you would like, this template only provides you with only one simple view. Using this template allows you to build your application from scratch, giving you the freedom to set up all the components as you like.
In this chapter, you will create an app that is called Hello-Contacts. This app renders your user's contact list in a UITableView that you will set up. Let's create a project for this app right now. Select File | New | Project in the menu bar. Next, select Single View Application from the list of project templates. When prompted to give your project a name, call it Hello-Contacts. Make sure that Swift is selected as the programming language for your app and uncheck all the Core Data and testing-related checkboxes; we won't need those right now.
Your configuration should resemble the following screenshot:
Once your application is configured, open the file named Main.storyboard. The storyboard file is used to lay out all of your application's views and to connect them to the code you write. The editor you use to manipulate your storyboard is called Interface Builder. Storyboards are a great way to edit your files and see the results of your actions immediately.
If you have used UITableView in the past, you may have used UITableViewController. The UITableViewController class is a subclass of a regular UIViewController. The difference is that UITableViewController contains a lot of setup that you would otherwise have to perform on your own. To fully understand how UITableView is configured and set up, you will not use UITableViewController now.
Take a look at the top bar in the Interface Builder window. There is a button there that has a circle with a square in it. This button opens the Object Library. The following screenshot shows you the Object Library and the button you can click to access it:
With the Object Library opened, look for UITableView. If you begin typing the name of the component you're looking for in the Object Library, all potential matches should automatically be filtered. Once you find the table view, drag it to the app's view. After doing this, use the white squares at the corners of the table view to make sure that the table covers the entire view.
If you look at the bottom of the window, you can see the dynamic viewport inspector. If you don't see it, try clicking on the name of the current preview device. In the inspector, select a device that either has a larger or a smaller screen than the current device. When you have done this, you will notice that the table view doesn't cover the viewport as nicely anymore. On smaller screens, you'll see that the table view has become larger than the view and on larger screens, the table view isn't large enough to cover the viewport:
To make sure your layout scales properly to fit any screen size you select, you use Auto Layout. Auto Layout enables you to create layouts that automatically adapt to any screen size that exists. Your layout currently uses fixed coordinates and dimensions to lay out the table view. For instance, your table view is set up to be positioned at (0, 0) with a size of (375, 667). This size is perfect for devices such as the iPhone 6, 6S, 7, and 8. But it wouldn't fit nicely with the iPhone Xs or iPad Pro. This combination of a view's position and size is called the frame.
Auto Layout uses constraints to define a layout instead of a frame. For instance, to make the table view fit the entire screen, you would add constraints that pin every edge of the table view to the corresponding edge of its superview. Doing so would make the table view match its superview's size at all times. The simplest way to set up constraints for this is to let Xcode add them for you. Let's use the dynamic viewport inspector to switch back to the initial device you had selected so we can add constraints from there.
First, ensure that the table view covers the entire viewport again, then click on the Resolve Auto Layout Issues button in the bottom-right corner of the Interface Builder screen and select Reset to Suggested Constraints from the menu that pops up:
Selecting this option automatically adds the constraints that Xcode considers required for your view. The constraints that were added by Xcode pin all of the table view's edges to its superview edges, which is precisely what you wanted to happen. You can manually inspect these constraints in the Document Outline on the left-hand side of the Interface Builder window:
Each constraint that got added describes how the table view should behave relative to another view. In this case, the other view is the superview. If you change the preview device in the dynamic viewport inspector, you should see that the table view always covers the entire screen. Try picking a couple of different screen sizes to make sure this works.
Now that you have a table view added to your view and its layout is exactly what you need, it is time to provide the table with some contents to display. To do this, you're going to write some code that uses Apple's Contacts.framework to fetch the app user's contacts list from their address book.
To display contacts in your table view, you must set up a few more things. First, you are going to need a table-view cell that displays contact information. All code for a custom table view cell should live in a UITableViewCell subclass. The design for your custom cell can be made in Interface Builder. When you make a design in Interface Builder, you can connect your code and the design using @IBOutlet. @IBOutlet is a connection between an object in the visual layout and a variable in your code.
Open your app's storyboard in Interface Builder and look for UITableViewCell in the Object Library. When you drag it into the table view that you have already added, your new cell is added as a prototype cell. A prototype cell functions as a blueprint for all cells the table view is going to display. That's right; you only need to set up a single cell to display many. You'll see how this works when you implement the code for your table-view cell. First, let's focus on the layout.
After dragging UITableViewCell to the table view, find and drag out UILabel and UIImageView. Both views should be added to the prototype cell. Arrange the label and image as shown in the following screenshot. After doing this, use the reset to suggested constraints feature you have used before to add Auto Layout constraints to the label and image. When you select both views after adding the constraints, you should see the same blue lines that are present in the following screenshot:
The blue lines from the image are a visual representation of the constraints that were added to lay out your label and image. In the image, you can see a constraint that offsets the label from the left side of the cell. Between the label and the image, you can see a constraint that defines the spacing between these two views. The line that runs through the cell horizontally shows that the label and image are centered on the vertical axis.
You can use Document Outline on the left side of Interface Builder to explore these constraints. The table-view cell design is now complete, it's time to implement the UITableViewCell subclass and create some @IBOutlets to connect design and code.
To create a new UITableViewCell subclass, you need to create a new file (File | New | File) and choose a Cocoa Touch file. Name the file ContactTableViewCell and select UITableViewCell as the superclass for your file, as shown in the following screenshot:
When you open the newly-created file, you'll see that two methods were added to the ContactTableViewCell for you. These methods are awakeFromNib() and setSelected(_:animated:). The awakeFromNib() method is called the very first time an instance of your class is created. This method is the perfect place to do some initial setup that should only be performed once for your cell.
The second method in the template is setSelected(_:animated:), you can use this method to perform some customizations for the cell when a user taps on it. You could, for instance, change the text or background color for a cell there. For now, delete both methods from the class and replace its contents with the following code:
@IBOutlet var nameLabel: UILabel! @IBOutlet var contactImage: UIImageView!
The preceding code should be the entire body for the ContactTableViewCell class. The variables in the class are annotated with @IBOutlet; this means that those variables can be connected with your prototype cell in Interface Builder. To do this, open Main. storyboard, select your prototype cell and look for the Identity Inspector in the sidebar on the right. Set the class property for your cell to ContactTableViewCell, as shown in the following screenshot. Setting this makes sure that your layout and code are correctly connected:
Next, select the table view cell that you added to the table view. Open the Connections Inspector in the right sidebar. Under the Outlets header, you'll find a list of names. Among those names, you can find the nameLabel and contactImage you added to ContactTableViewCell. Drag from the circle next to the nameLabel towards the label inside of your cell. By doing this, you connect the @IBOutlet that was created in code to its counterpart in the layout. Perform the same steps outlined in the preceding paragraph for the image, as shown in the following screenshot:
The last step is to provide a reuse-identifier for your cell. The table view uses the reuse-identifier so it can reuse instances of table-view cells. Cell-reuse is an optimization feature that will be cover in depth later in this chapter.
To set the reuse-identifier, open the Attributes inspector after selecting your cell. In the Attributes inspector, you'll find, and an input field labeled Identifier. Set this field to the ContactTableViewCell value.
With your layout fully set up, we need to take a couple more steps to make the table view show a list of contacts by assigning it a data source and delegate.
One easily-overlooked fact about the table view is that no matter how simple it might seem to use one in your app, it's one of the more complex components of UIKit. Some of the complexity is exposed when you add a table view to a regular view controller instead of using UITableViewController. For instance, you had to manually set up the layout, so your table view covered the viewport. Then, you had to manually set up a prototype cell to display data in.
The next step toward displaying contacts to your user is providing the table view with information about the contents it should show. To do this, you must implement the data source and delegate for the table view. These properties use advanced concepts that you may have seen before, you probably just weren't aware of them yet. Let's make sure you know exactly what is going on.
Throughout the iOS SDK and the Foundation framework, a design pattern named delegation is used. Delegation allows an object to have another object perform work on its behalf. When implemented correctly, it's a great way to separate concerns and decouple code within your app. The following figure illustrates how UITableView uses delegation for its data source using UITableViewDataSource:
The table view uses the help of two objects to function correctly. One is delegate, and the other is dataSource. Any time you use a table view, you must configure these two objects yourself. When the time comes for the table view to render its contents, it asks dataSource for information about the data to display. delegate comes into play when a user interacts with the items in the table view.
If you look at the documentation for UITableView, you can find the delegate property. The type for delegate is UITableViewDelegate?. This tells you two things about delegate. First of all, UITableViewDelegate is a protocol. This means that any object can act as a delegate for a table view, as long as it implements the UITableViewDelegate protocol. Second, the question mark behind the type name tells you that the delegate is an Optional property. An Optional property either has a value of the specified type, or it is nil. The table view's delegate is Optional because you do not haveto set it to create a functioning table view.
A protocol, such as UITableViewDelegate, defines a set of properties and methods that must be implemented by any type that wants to conform to the protocol. Not all methods must be explicitly implemented by conforming objects. Sometimes, a protocol extension provides a reasonable default implementation. You can read more about this in Chapter 6, Writing Flexible Code With Protocols And Generics.
In addition to delegate, UITableView has a dataSource property. The data source's type is UITableViewDataSource?, and just like UITableViewDelegate, UITableViewDataSource is a protocol. However, UITableViewDelegate only has optional methods, meaning you don't need to implement any methods to conform to UITableViewDelegate. UITableViewDataSource does have required methods. The methods that need to be implemented are used to provide the table view with just enough information to be able to display the correct amount of cells with the right content in them.
If this is the first time you're learning about protocols and delegation, you might feel a little bit lost right now. That's OK; you'll get the hang of it soon. Throughout this book, your understanding of topics such as these will improve bit by bit. You will even learn about a concept called protocol-oriented programming! For now, it's important that you understand that a table view asks a different object for the data it needs to show and that it also uses a different object to handle certain user interactions.
We can break the flow of displaying contents in a table view down into a couple of steps:
The table view needs to reload the data
The table view checks whether a
dataSource
is set, and asks it for the number of sections it should render
Once the number of sections is passed back to the table view, the
dataSource
is asked for the number of items for each section
With knowledge about the number of sections and items that need to be shown, the table view asks its
dataSource
for the cells it should display
After receiving all of the configured cells, the table view can finally render these cells to the screen
These steps should give you a little bit more insight into how a table view uses another object to figure out the contents it should render. This pattern is compelling because it makes the table view an extremely flexible component. Let's put some of this newfound knowledge to use!
