35,99 €
iOS 13 comes with features ranging from Dark Mode and Catalyst through to SwiftUI and Sign In with Apple. If you're a beginner and are looking to experiment and work with these features to create your own apps, then this updated fourth edition gets you off to a strong start. The book offers a comprehensive introduction for programmers who are new to iOS, covering the entire process of learning the Swift language, writing your own apps, and publishing them on the App Store. This edition is updated and revised to cover the new iOS 13 features along with Xcode 11 and Swift 5. The book starts with an introduction to the Swift programming language, and how to accomplish common programming tasks with it. You'll then start building the user interface (UI) of a complete real-world app, using the latest version of Xcode, and also implement the code for views, view controllers, data managers, and other aspects of mobile apps. The book will then help you apply the latest iOS 13 features to existing apps, along with introducing you to SwiftUI, a new way to design UIs. Finally, the book will take you through setting up testers for your app, and what you need to do to publish your app on the App Store. By the end of this book, you'll be well versed with how to write and publish apps, and will be able to apply the skills you've gained to enhance your apps.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 559
Veröffentlichungsjahr: 2020
Copyright © 2020 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 authors, 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: Pawan RamchandaniAcquisition Editor:Ashitosh GuptaContent Development Editor:Akhil NairSenior Editor: Mohammed Yusuf ImaratwaleTechnical Editor: Jane DsouzaCopy Editor:Safis EditingProject Coordinator:Kinjal BariProofreader: Safis EditingIndexer:Pratik ShirodkarProduction Designer:Aparna Bhagat
First published: January 2017 Second published:January 2018 Third published: December 2018 Fourth published: January 2020
Production reference: 1230120
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83882-190-6
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,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
Fully searchable for easy access to vital information
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.
Ahmad Saharis a trainer, presenter, and consultant at Tomafuwi Productions, specializing in conducting training courses for macOS and iOS, macOS Support Essentials certification courses, and iOS Development courses. He is a member of the DevCon iOS and MyCocoaHeads online communities in Malaysia, and has conducted presentations and talks for both groups. In his spare time, he likes building and programming LEGO Mindstorms robots.
Craig Claytonis a self-taught, senior iOS engineer at Adept Mobile, specializing in building mobile experiences for NBA and NFL teams. He also volunteered as the organizer of the Suncoast iOS meetup group in the Tampa/St. Petersburg area for 3 years, preparing presentations and hands-on talks for this group and other groups in the community. He has also launched Cocoa Academy online, which specializes in bringing a diverse list of iOS courses, ranging from building apps to games for all programming levels, to the market.
Cecil Costa, also known as Eduardo Campos in Latin countries, is a Euro-Brazilian freelance developer who has been learning about computers since the time he got his first PC in 1990. From then on, he kept learning about programming languages, computer architecture, and computer science theory.
Learning is his passion as well as teaching; this is the reason why he worked as a trainer and a books author. He has been giving on-site courses for many companies.
He is also the author of three Swift books and two video courses.
Nowadays, Cecil Costa teaches through online platforms, helping people from every part of the world.
Chris Barker is a senior iOS developer and tech lead for fashion retailer N Brown, where he heads up the iOS team, building apps for their major brands. Having now worked in the IT industry for over 22 years, Chris has started developing .NET applications for retailer.
In 2014, he made his move into mobile app development with digital agency Openshadow at MediaCityUK. Here he worked on mobile apps for clients such as Louis Vuitton and L'Oréal Paris.
Chris often attends and speaks at his local iOS developer meetup - NSManchester. Most recently he attended Malaga Mobile in Spain where he spoke about accessibility in mobile apps. Over the past 2 years, Chris has been a regular speaker at CodeMobile and will be returning to speak again in 2020.
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
iOS 13 Programming for Beginners Fourth Edition
About Packt
Why subscribe?
Contributors
About the authors
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
Code in Action
Conventions used
Get in touch
Reviews
Section 1: Swift
Getting Familiar with Xcode
Technical requirements
Downloading and installing Xcode from the App Store
Understanding the Xcode user interface
Running the app in the Simulator
Understanding the No Device and Build Only Device menu items
Using an iOS 13 device for development
Trusting the Developer App certificate on your iOS device
Connecting an iOS device wirelessly
Summary
Simple Values and Types
Technical requirements
Understanding Swift playgrounds
Customizing fonts and colors
Exploring data types
Storing integers
Storing floating-point numbers
Storing Booleans
Storing strings
Using common data types in the playground
Exploring constants and variables
Understanding type inference and type safety
Using type annotation to specify a type
Type safety
Exploring operators
Using arithmetic operators
Using compound assignment operators
Using comparison operators
Using logical operators
Performing string operations
Using the print() instruction
Summary
Conditionals and Optionals
Technical requirements
Introducing conditionals
Using if statements
Using switch statements
Introducing optionals
Using optionals and optional binding
Summary
Range Operators and Loops
Technical requirements
Range operators
Loops
The for-in loop
The while loop
The repeat-while loop
Summary
Collection Types
Technical requirements
Understanding arrays
Creating an array
Checking the number of elements in an array
Adding a new item to an array
Accessing an array element
Assigning a new value to an index
Removing an item from an array
Iterating over an array
Understanding dictionaries
Creating a dictionary
Checking the number of elements in a dictionary
Adding a new item to a dictionary
Accessing a dictionary element
Assigning a new value to a key
Removing an item from a dictionary
Iterating over a dictionary
Understanding sets
Creating a set
Checking the number of elements in a set
Adding a new item to a set
Checking whether a set contains an item
Removing an item from a set
Iterating over a set
Set operations
Set membership and equality
Summary
Functions and Closures
Technical requirements
Understanding functions
Creating a function
Using custom argument labels
Using nested functions
Using functions as return types
Using functions as parameters
Using a guard statement to exit a function early
Understanding closures
Simplifying closures
Summary
Classes, Structures, and Enumerations
Technical requirements
Understanding classes
Creating a class declaration
Making an instance of the class
Making a subclass
Overriding a superclass method
Understanding structures
Creating a structure declaration
Making an instance of the struct
Value types versus references types
Deciding which to use
Understanding enumerations
Creating an enumeration
Summary
Protocols, Extensions, and Error Handling
Technical requirements
Understanding protocols
Creating a protocol declaration
Understanding extensions
Adopting a protocol via an extension
Creating an array of different types of objects
Exploring error handling
Summary
Section 2: Design
Setting Up the Basic Structure
Technical requirements
Useful terms
Touring the Let's Eat app
Using the Explore screen
Using the Locations screen
Using the Restaurant List screen
Using the Restaurant Detail screen
Using the Review Form screen
Using the Map screen
Creating a new Xcode project
Setting up a Tab Bar Controller Scene and Launch screen
Setting the titles of the Tab Bar's buttons
Embedding view controllers in navigation controllers
Adding the Assets.xcassets file
Configuring the Launch screen's background color
Adding a logo and constraints to the Launch screen
Adding the icons for the Explore and Map buttons
Summary
Building Your App Structure in Storyboard
Technical requirements
Adding a collection view to the Explore screen
Adding a Cocoa Touch Class file to your project
Connecting outlets in storyboard to the view controller
Configuring data source methods for the collection view
Setting the delegate and data source properties of the collection view
Adopting the UICollectionViewDataSource and UICollectionViewDelegate protocols
Adding a section header to the collection view
Creating a custom color
Configuring the collection view cell and section header size
Presenting a view modally
Adding a button to the collection view header
Adding a new view controller scene
Adding the Cancel and Done buttons to the navigation bar
Summary
Finishing Up Your App Structure in Storyboard
Technical requirements
Adding a table view to the Locations screen
Implementing the Restaurant List screen
Declaring the RestaurantListViewController class
Adopting the delegate and data source protocols
Presenting the Restaurant List screen
Implementing the Restaurant Detail screen
Implementing the Review Form screen
Implementing the Map screen
Summary
Modifying and Configuring Cells
Technical requirements
Modifying the Explore screen section header
Adding Auto Layout to the Explore screen's section header
Modifying the exploreCell collection view cell
Modifying the restaurantCell collection view cell
Adding Auto Layout constraints to the restaurantCell collection view cell
Configuring the locationCell table view cell
Summary
Section 3: Code
Getting Started with MVC and Collection Views
Technical requirements
Understanding the MVC design pattern
Exploring controllers and classes
Understanding collection views
Revisiting the Explore and Restaurant List screens
Summary
Getting Data into Collection Views
Technical requirements
Understanding model objects
Understanding .plist files
Creating a structure to represent a cuisine
Implementing a data manager class to read data from a .plist
Using the data manager to initialize ExploreItem instances
Displaying data in a collection view
Connecting the outlets in exploreCell
Implementing additional data manager methods
Updating the data source methods in ExploreViewController
Summary
Getting Started with Table Views
Technical requirements
Understanding table views
Creating LocationViewController
Connecting the table view to LocationViewController
Adding the data source and delegate methods
Adding location data for the table view
Creating a property list (.plist) file
Adding data to the .plist file
Creating LocationDataManager
Displaying data in a table view using LocationDataManager
Cleaning up the user interface
Summary
Getting Started with MapKit
Technical requirements
Understanding and creating annotations
Introducing MKAnnotation
Creating the RestaurantItem class
Creating MapDataManager
Creating the DataManager protocol
Refactoring MapDataManager
Refactoring ExploreDataManager
Adding annotations to a map view
Creating MapViewController
Connecting the outlets for the map view to MapViewController
Setting the map view region to be displayed
Displaying annotations on the map view
Creating custom annotations
Going from the Map screen to the Restaurant Detail screen
Creating and configuring a storyboard reference
Performing the showDetail segue
Passing data to the Restaurant Detail screen
Organizing your code
Refactoring ExploreViewController
Using the // MARK: syntax
Refactoring RestaurantListViewController
Refactoring LocationViewController
Refactoring MapViewController
Summary
Getting Started with JSON Files
Technical requirements
Getting data from JSON files
What is an API?
Understanding the JSON format
Creating RestaurantAPIManager
Using data from JSON files in your app
Storing a user-selected location in LocationViewController
Adding a view controller for the section header in the Explore screen
Connecting the section header's label to ExploreViewController
Adding an unwind action method to the Done button
Selecting only one location in the Location screen
Passing location and cuisine information to RestaurantListViewController
Creating a view controller for the cells on the Restaurant List screen
Connecting the outlets for RestaurantCell
Creating RestaurantDataManager
Configuring MapDataManager to use RestaurantDataManager
Displaying a custom UIView to indicate no data available
Displaying a list of restaurants on the Restaurant List screen
Summary
Displaying Data in a Static Table View
Technical requirements
Setting up outlets for RestaurantDetailViewController
Displaying data in the static table view
Passing data from RestaurantListViewController to RestaurantDetailViewController
Summary
Getting Started with Custom UIControls
Technical requirements
Creating a custom UIControl object
Displaying stars in your custom UIControl object
Adding support for touch events
Implementing an unwind method for the Cancel button
Creating ReviewFormViewController
Summary
Getting Started with Cameras and Photo Libraries
Technical requirements
Understanding filters
Creating a scrolling list of filters
Creating a view controller for the filter cell
Creating a View Controller for the Photo Filter screen
Getting permission to use the camera or photo library
Summary
Understanding Core Data
Technical requirements
Introducing Core Data
Implementing Core Data components for your app
Creating a data model
Creating ReviewItem
Creating RestaurantPhotoItem
Creating a Core Data manager
Creating ReviewDataManager
Summary
Saving and Loading from Core Data
Technical requirements
Understanding how saving and loading works
Adding a restaurantID property to RestaurantItem
Updating ReviewFormViewController to save reviews
Passing RestaurantID to ReviewFormViewController
Updating PhotoFilterViewController to save photos
Displaying saved reviews and photos on the Restaurant Detail screen
Calculating a restaurant's overall rating
Summary
Section 4: Features
Getting Started with Dark Mode
Technical requirements
Turning on Dark Mode in the simulator
Updating the Launch screen to work with Dark Mode
Updating the Explore screen to work with Dark Mode
Updating the Restaurant List screen to work with Dark Mode
Updating the Restaurant Detail screen to work with Dark Mode
Updating the Reviews View Controller scene and NoDataView to work with Dark Mode
Updating the Photo Reviews View Controller Scene to work with Dark Mode
Summary
Getting Started with Mac Catalyst
Technical requirements
Cleaning up the design
Updating the app to work on iPad
Checking device type
Updating ExploreViewController for iPad
Updating RestaurantListViewController for iPad
Updating the Restaurant Detail screen for iPad
Updating the app to work on macOS
Summary
Getting Started with SwiftUI
Technical requirements
Creating a SwiftUI project
Working with text
Combining Views using Stacks
Working with images
Using UIKit and SwiftUI Views together
Composing the Restaurant Detail screen
Summary
Getting Started with Sign In with Apple
Technical requirements
Adding a login screen
Displaying a Sign in with Apple button
Implementing delegate methods and button actions
Passing user information to ExploreViewController
Summary
Testing and Submitting Your App to the App Store
Technical requirements
Getting an Apple Developer account
Generating a certificate signing request
Creating development and distribution certificates
Registering an App ID
Registering your devices
Creating provisioning profiles
Creating icons for your app
Creating screenshots for your app
Creating an App Store listing
Creating an archive build
Completing the information in App Store Connect
Testing your app
Testing your app internally
Testing your app externally
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Welcome to iOS 13 Programming for Beginners. This book is the fourth edition of the iOS Programming for Beginners series, and has been fully updated for iOS 13, macOS 10.15 Catalina, and Xcode 11.
In this book, you will build a restaurant reservation app calledLet's Eat. You will start off by exploring Xcode, Apple's programming environment, also known as its Integrated Development Environment(IDE). Next, you will start learning the foundations of Swift, the programming language used in iOS apps, and see how it is used to accomplish common programming tasks.
Once you have a solid foundation of using Swift, you will start creating the visual aspects of theLet's Eatapp. During this process, you will work with storyboards and connect your app's structure together using segues.
With your user interface complete, you will then add code to implement your app's functionality. To display your data in a grid, you will use collection views, and to display your data in a list, you will use table views. You will also look at how to add basic and custom annotations on to a map. Finally, it's time to get real data; you will look at what an Application Programming Interface (API) is and how you can get actual restaurant data into your collection views, table views, and map.
You now have a complete app, but how about adding some bells and whistles? The first place where you can add a feature will be the restaurant detail page, where users can add restaurant reviews. Here, users will be able to take or choose a picture and apply a filter to their picture. They will also be able to give the restaurant a rating as well as a review. You will save this data using Core Data.
After that, you will implement the latest iOS 13 features. You will make your app support Dark Mode, which gives your app a fresh and exciting user interface. Then, you will modify your app to work on both iPhone and iPad and make it work on the Mac Catalyst as well using Project Catalyst. After that, you will learn how to develop views using SwiftUI, a great new way of specifying what the user interface should look like. Finally you'll modify your app to use Sign in with Apple, to further personalize the app to a user.
When you have added some bells and whistles, you can test the app with internal and external testers, and finally get it into the App Store.
This book is for you if you are a programmer who is completely new to Swift, iOS, or programming and want to make iOS applications. However, you'll also find this book useful if you're an experienced programmer looking to explore the latest iOS 13 features.
Chapter 1, Getting Familiar with Xcode,takes you through a tour of Xcode and talks about all the different panes that you will use throughout the book.
Chapter 2, Simple Values and Types,deals with how values and types are implemented by the Swift language.
Chapter 3, Conditionals and Optionals,shows how if and switch statements are implemented, and how to implement variables that may or may not have a value.
Chapter 4, Range Operators and Loops,shows how to work with ranges and the different ways loops are implemented in Swift.
Chapter 5, Collection Types,covers the common collection types, which are arrays, dictionaries, and sets.
Chapter 6, Functions and Closures,covers how you can group instructions together using functions and closures.
Chapter 7, Classes, Structures, and Enumerations,talks about how complex objects containing state and behaviour are represented in Swift.
Chapter 8, Protocols, Extensions, and Error Handling,talks about creating protocols complex data types can adopt, extending the capabilities of existing types, and how to handle errors in your code.
Chapter 9, Setting Up the Basic Structure,deals with creating the Let's Eat app, adding graphical assets, and setting up the initial screen the users will see.
Chapter 10, Building Your App Structure in Storyboard,covers setting up the main screen for the Let's Eat app.
Chapter 11, Finishing Up Your App Structure in Storyboard,covers setting up the remaining screens for the Let's Eat app.
Chapter 12, Modifying and Configuring Cells,is about designing the table and collection view cells in a storyboard.
Chapter 13, Getting Started with MVC and Collection Views,concerns working with collection views and how you can use them to display a grid of items.
Chapter 14, Getting Data into Collection Views,concerns the incorporation of data into collection views.
Chapter 15, Getting Started with Table Views,teaches you to work with table views and takes an in-depth look at dynamic table views.
Chapter 16, Getting Started with MapKit,deals with working with MapKit and adding annotations to a map. You will also create custom annotations for your map.
Chapter 17, Getting Started with JSON Files,involves learning how to use a data manager to read a JSON file and use the data inside your app.
Chapter 18, Displaying Data in a Static Table View,teaches you how to populate a static table view with data passed from one view controller to another using segues.
Chapter 19, Getting Started with Custom UIControls, takes a look at how to create your own custom views.
Chapter 20, Getting Started with the Cameras and Photo Libraries, talks about working with the device's camera and photo library.
Chapter 21, Understanding Core Data, teaches us the basics of using core data.
Chapter 22, Saving and Loading from Core Data, wraps up reviews and photos by saving them using core data.
Chapter 23, Getting Started with Dark Mode,shows how to add Dark Mode to your app.
Chapter 24, Getting Started with Mac Catalyst,deals with modifying your app to work well on the iPad's larger screen, and to make it work on a Mac.
Chapter 25, Getting Started with SwiftUI,is about building a custom UI using Apple's new SwiftUI technology.
Chapter 26, Getting Started with Sign In with Apple,provides instructions on how to implement Sign in with Apple into your app.
Chapter 27, Testing and Submitting Your App to the App Store,concerns how to submit apps for testing as well as submitting apps to the App Store.
This book has been completely revised for iOS 13, macOS 10.15 Catalina, Xcode 11 and Swift 5. Section 4 of this book also covers the latest technologies introduced by Apple during WWDC 2019, which are Dark Mode, Mac Catalyst, Swift UI and sign in with Apple.
To complete all the exercises in this book, you will need:
A Mac computer running macOS 10.15 Catalina or later
Xcode 11.2.1 or later
To check if your Mac supports macOS 10.15 Catalina, see this link: https://support.apple.com/en-us/HT210222. If your Mac is supported, you can update macOS using Software Update in System Preferences.
To get the latest version of Xcode, you can download it from the Mac App Store.
Most of the exercises can be completed without an Apple Developer account and use the iOS Simulator. If you wish to test the app you are developing on an actual iOS device, you will need a free or paid Apple Developer account, and the following chapters require a paid Apple Developer account:
Chapter 26, Getting Started with Sign In with AppleChapter 27, Testing and Submitting Your App to the App Store
Instructions on how to get a paid Apple Developer account are in Chapter 27, Testing and Submitting Your App to the App Store.
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.packtpub.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
.
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/iOS-13-Programming-for-Beginners. 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 athttps://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://static.packt-cdn.com/downloads/9781838821906_ColorImages.pdf.
Visit the following link to check out videos of the code being run:
http://bit.ly/2RhXuHk
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "So, this is a very simple function, named serviceCharge()."
A block of code is set as follows:
func functionName(paramater1: parameterType, ...) -> returnType { code}
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "LaunchXcodeand clickCreate a new Xcode project:"
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.packtpub.com/support/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.
Welcome to part one of this book. In this part, you will begin by exploring Xcode, Apple's programming environment, which is also known as the Integrated Development Environment (IDE). Next, you will start learning the foundations of Swift 5, the programming language used in iOS apps, and see how it is used to accomplish common programming tasks.
This part comprises the following chapters:
Chapter 1
,
Getting Familiar with Xcode
Chapter 2
,
Simple Values and Types
Chapter 3
,
Conditionals and Optionals
Chapter 4
,
Range Operators and Loops
Chapter 5
,
Collection Types
Chapter 6
,
Functions and Closures
Chapter 7
,
Classes, Structures, and Enumerations
Chapter 8
,
Protocols, Extensions, and Error Handling
By the end of this part, you'll understand the process of creating an app and running it on a simulator or device, and you'll have a working knowledge of how to use the Swift programming language, in order to accomplish common programming tasks. This will prepare you for the next chapter, and will also enable you to create your own Swift programs. Let's get started!
Welcome to iOS 13 Programming for Beginners. I hope you will find this a useful introduction to writing and publishing iOS 13 apps on the App Store.
This book is divided into four parts. Each is designed to accomplish a specific set of goals.
In Section 1, Swift, you start by learning Swift 5.1, which is the latest version of the Swift language. Swift is the programming language used to write apps for all Apple hardware. You'll see how common programming tasks are accomplished in Swift. At the end of this part, you should have a working knowledge of the Swift language.
In Section 2, Design, you'll create the design of an iOS 13 application from scratch using storyboards. This is accomplished using Xcode's Interface Builder, and coding is kept to a minimum. At the end of this part, you should have a clear idea of the app's user interface and flow.
Section 3, Code, will focus on coding. You will learn many important iOS app development concepts, and as you go along, you'll learn strategies and techniques that you can use in your own apps.
Section 4,Features, covers the exciting new technologies first introduced by Apple at WWDC 2019, such as Dark Mode, Catalyst, SwiftUI, and Sign In with Apple. You'll also learn how to create resources for App Store submission, submit your app to the App Store, and beta test your app.
The app you'll write is a restaurant reservation app named Let's Eat. This app was originally written by Craig Clayton, who wrote the previous edition of this book. I have updated this app for the latest version of Xcode and iOS.
In this chapter, we'll cover the following topics:
Downloading and installing Xcode from the App Store
Understanding the Xcode user interface
Running the app in the Simulator
Using an iOS 13 device for development
To do the exercises for this chapter, you will need the following:
An Apple Mac computer running macOS 10.15 Catalina
An Apple ID (if you don't have one, you will create one in this chapter)
Optionally, an iOS device running iOS 13
The Xcode project for this chapter is in the Chapter01 folder of the code bundle for this book, which can be downloaded here:
https://github.com/PacktPublishing/iOS-13-Programming-for-Beginners.
You'll start by downloading Xcode, Apple's integrated development environment for developing iOS apps from the App Store.
Check out the following video to see the code in action:
http://bit.ly/38B50D5
Before you begin writing iOS Apps, you need to download and install Xcode from the App Store. Perform the following steps:
Open the App Store on your Mac (it's in the Apple menu).
In the search field in the top-right corner, type
Xcode
and press the
Return
key.
You should see Xcode in the search results. Clic
k
Get
and click
Install
.
If
you have an Apple ID, type it in the
Apple ID
text box. If you don't have one, click the
Create Apple ID
button and follow the step-by-step instructions to create one:
Once Xcode has been installed, launch it. You should see the following
Welcome to Xcode
screen:
If this is the first time you have launched Xcode, you will see No Recent Projects in the right-hand panel. If you have previously created projects, then you will see them listed in the right-hand panel. ClickCreate a new Xcode projectin the left-hand pane.
You will see the new project screen as follows:
Across the top of this screen, you can select one of the following items: iOS, watchOS, tvOS, macOS, and Cross-platform. iOS should already be selected. Then, choose Single View App and click on Next.
You will see an options screen for a new project:
This options screen has the following eight items to complete or choose:
Product Name
: The name of your app. Enter
ExploringXcode
in the text field.
Team
: The Developer Account Team for this project. Leave it as it is for now.
Organization Name
: The name of your company. Just put your own name here for now.
Organization Identifier
: Used in conjunction with the
Product Name
to create a unique identifier for your app on the App Store. Normally, reverse DNS notation is used. Enter
com.myname
for now.
Bundle Identifier
: Automatically created by combining your
Product Name
and your
Organization Identifier
. Used to uniquely identify your app on the App Store.
Language
: The programming language to be used. Set this to
Swift
.
User Interface
: Set this to
Storyboard
.
Checkboxes
: These checkboxes are used to include code for core data, unit tests, and UI tests. Leave them unchecked for now.
Click Next when you're done.
Choose a location to save your project, such as the
Desktop
or
Documents
folder, and click
Create
:
If you see a dialog box saying
No author information was supplied by the version control system
, click
Fix
.
You will see the
Source Control
preference screen as follows:
Enter the following information:
Author Name
:
Your own name
Author Email
:
Your email address
The Xcode main window will appear.
Fantastic! You have now successfully downloaded and installed Xcode, and in the next section, we will study the Xcode user interface.
Xcode is the tool you use to write apps, and you will learn about the Xcode user interface in this section. You'll become familiar with the structure of a project in Xcode and learn how to navigate between and use basic project components.
Let's go over each of the different parts:
The following are the elements shown in the preceding screenshot:
Toolbar
: Used to build and run your apps, and view the progress of running tasks. Contains the
Play
button (1), the
Stop
button (2), the
Scheme
menu (3), and the
Activity View
(4):
The
Play
button is used to build and run your app.
The
Stop
button stops any currently running apps.
The
Scheme
menu shows the specific target to be built (
Exploring Xcode
), and the destination (Simulator or device) to run the target on (
iPhone Simulator
).
Schemes and destinations are distinct. Schemes specify the settings for building, running, testing, profiling, analyzing, and archiving your project. Destinations specify installation locations for your app. Typically, a scheme exists for each target in your project. Destinations exist for physical devices and simulators.
The
Activity
View
displays the progress of running tasks.
Window Pane buttons
: Used to configure your work environment. Contains the
Object library
(1),
Version Editor
(2), and
Navigator
,
Debug,
and
Inspector
buttons (3):
The
Library
button displays user interface elements, code snippets, and other resources.
The
Version
Editor
button shows versions of the same file.
The
Navigator, Debug
, and
Inspector
buttons toggle the
Navigator area,
the
Debug area
and the
Inspector area
on and off.
Navigator area
: Provides quick access to the various parts of your project. The
Project navigator
is displayed by default.
Editor area
: Allows you to edit source code, user interfaces, and other resources.
Inspector area
: Allows you to view and edit information about items selected in the
Navigator area
or
Editor area
.
Debug area
: Contains the debug bar, the variables view, and the
Console
.
Don't be overwhelmed by all the different parts, you'll learn about them in more detail in later chapters. Now that you are familiar with the Xcode interface, we will run the app you just created in the Simulator, which displays a representation of your iOS device.
The Simulator gives you an idea of how your app would look and behave if it were running on a device. It can model a number of different types of hardware—all the screen sizes and resolutions for both iPad and iPhone—so you can simulate your app on every device you're developing for.
To run the app in the Simulator, perform the following steps:
Click the
Scheme
menu in the toolbar and you will see a list of Simulators. Choose
iPhone 11
from this menu:
Click the Play button to install and run your app on the currently selected Simulator. You can also use the
command
+
R
keyboard shortcut.
If you see the
Developer Tools Access
dialog box, enter the Mac's admin
Username
and
Password
and click
Continue
:
The Simulator app will launch and show a representation of an
iPhone 11
. Your app displays a white screen, as you have not yet added anything to your project:
Switch back to Xcode and click on the Stop button (or type
Command - .
) to stop the currently running project.
You have just created and run your first iOS app in the Simulator! Great job!
If you look at the Scheme menu, you may be wondering about what the No Device and Build Only Device menu items are for. Let's take a look at them.
You learned how to choose a Simulator in the Scheme menu to run your app in the previous section. But what are the No Device and Build Only Device menu items for? Well, Xcode not only allows you to run apps on the Simulator, but it also allows you to run apps on actual iOS devices, and prepare apps for submission to the App Store.
By clicking the Scheme menu in the toolbar, you will see the entire menu, and at the top of the menu are the No Device and Build Only Device sections:
The No Device section currently displays text stating No devices connected to 'My Mac'... because you currently don't have any iOS devices connected to your computer. If you were to plug in an iOS device, it would appear in this section, and you would be able to run the apps you develop on it for testing. Running your apps on an actual device is recommended as the Simulator will not accurately reflect the performance characteristics of an actual iOS device, and does not have some hardware features and software APIs that actual devices have.
The Build Only Device section has only one option, Generic iOS Device. This is used when you need to archive your app prior to submitting it to the App Store. You'll learn how to do this in the last chapter of this book.
Now let's see how to build and run your app on an actual iOS 13 device. The vast majority of the instructions in this book do not require you to have an iOS device though, so if you don't have one, skip the next section and go straight to Chapter 2, Simple Values and Types.
Although you'll be able to go through most of the exercises in this book using the Simulator, it is recommended to build and test your apps on an actual iOS device, as the Simulator will not be able to simulate some hardware components and software APIs.
In addition to your device, you'll need an Apple ID or a paid Apple Developer account to build and run your app on your device. You'll use the same Apple ID that you used in the App Store for now:
Use the USB cable to connect the iOS device to your Mac.
In the
Scheme
menu, choose your device (
iPhone
in this case):
Wait for Xcode to finish indexing and processing, which will take a while. Once complete,
Ready
will be displayed in the status window.
Run the project by hitting the
Play
button (or use
command
+
R
). You will get the following error:
Signing for "Exploring Xcode" requires a development team
:
This is because a digital certificate is required to run the app on an iOS 13 device, and you need to add an Apple ID or a Developer account to Xcode so the digital certificate can be generated.
Click the
Add Account...
button:
The Xcode
Preferences
window appears with the
Accounts
pane selected. Enter your
Apple ID
and click
Next
. Note that you can create a different
Apple ID
if you wish using the
Create Apple ID
button:
Enter your password when prompted. After a few minutes, the
Accounts
pane will display your account settings:
Close the
Preferences
window when you're done by clicking the red button in the top-left corner.
In Xcode's editing area, Click
Signing & Capabilities
. Make sure
Automatically manage signing
is ticked and
Personal Team
is selected from the
Tea
m
pop-up menu:
If you still see errors in this screen, try changing your
Bundle Identifier
by typing some random characters into it, for example,
com.12345myname.Exploring-Xcode
.
Everything should work now when you build and run, and your app will be installed on your iOS device. However, it will not launch and you will see the following message:
This means you need to trust the certificate that has been installed on your device.
In the next section, we will see how to do that.
A Developer App certificate is a special file that gets installed on your iOS device along with your app. Before your app can run, you need to trust it. Let's do that now:
On your iOS 13 device, tap
Settings
.
Tap
General
.
Tap
Device Management
:
Tap
Apple Development
:
Tap
Trust "Apple Development: "
:
Tap
Trust
:
You should see the following, which shows the app is now trusted:
Click the Play button in Xcode to build and run again. You'll see your app launch and run on your iOS device.
Congratulations! Note that you have to connect your iOS 13 device to your Mac using the USB cable to build and run your app, so in the next section we'll see how we can connect over Wi-Fi.
Unplugging and replugging your iOS device using USB gets pretty cumbersome after a while, so you'll configure Xcode to connect to your iOS device over Wi-Fi as follows:
Make sure your Mac and iOS device are on the same wireless network.
Choose
Window
|
Devices and Simulators
from the menu bar:
Click on the checkbox marked
Connect via network
:
Awesome! Your iOS device is now connected wirelessly to Xcode, and you no longer need the USB cable connected.
In this chapter, you learned how to download and install Xcode on your Mac. You familiarized yourself with the different parts of the Xcode user interface. You created your first iOS app, selected a Simulator, and built and ran the app. You learned what the Generic iOS Device menu item is for. You also learned how to connect an iOS device to Xcode via USB so that you can run the app on it, how to add an Apple ID to Xcode so the necessary digital certificates can be created and installed on your device, and how to trust the certificate on your device. Finally, you learned how to connect to your device over Wi-Fi, so you no longer need to plug and unplug your device every time you want to run an app.
You now know how to download and install Xcode from the App Store, the different panels in Xcode, how to add Developer credentials, and how to connect an iOS device for development using USB and Wi-Fi.
In the next chapter, we'll start exploring the Swift language using Swift Playgrounds, and learn how simple values and types are implemented in Swift.
Now that you have had a short tour of Xcode, let's look at the Swift programming language.
First, you'll explore Swift playgrounds, an interactive environment where you can type in Swift code and have it execute and display results immediately. You'll study how Swift stores various types of data, and how it performs operations on that data. You'll also look at some cool Swift features such as type inference and type safety, which help you to write code more concisely and avoid common errors. Finally, you'll learn how to perform common operations on data and how to print messages to the Debug area to help you troubleshoot issues.
By the end of this chapter, you should be able to write simple programs that can process letters and numbers.
The following topics will be covered:
Understanding Swift playgrounds
Exploring data types
Exploring constants and variables
Understanding type inference and type safety
Exploring operators
Using the
print()
function
To do the exercises for this chapter, you will need the following:
An Apple Mac computer running macOS 10.15 Catalina
Xcode 11 installed (refer to
Chapter 1
,
Getting Familiar with Xcode
, for instructions on how to install Xcode)
The Xcode playground for this chapter is in the Chapter02 folder of the code bundle for this book, which can be downloaded here:
https://github.com/PacktPublishing/iOS-13-Programming-for-Beginners.
You'll start by creating a new playground in the next section, where you can type in the code presented in this chapter.
Check out the following video to see the code in action:
http://bit.ly/36prN3j
Playgrounds are an interactive coding environment. You type code in the left-hand pane, and the results are displayed immediately in the right-hand pane. You can also use print() to display anything you like in the Debug area. It's a great way to experiment with code and to explore system APIs. Let's get started!
To create a playground, launch Xcode. Click
Get started with a playground
:
If you don't see the welcome screen, you can also choose
File
|
New
|
Playground...
from the
Xcode
menu bar to create a new playground.
The template screen appears.
iOS
should already be selected. Choose
Blank
and click
Next
:
Name your playground
SimpleValues
and save it anywhere you like. Click
Create
when done:
You should see the playground on the screen:
As you can see, it's much simpler than an Xcode project. Let's look at the interface in more detail:
Activity View
(
1
): Shows the current operation or status.
Window pane buttons
(
2
): As we saw in the previous chapter, the first button displays the Library. The remaining three buttons toggle the Navigator, Debug, and Inspector areas.
Editor area
(
3
): You write code here.
Results area
(
4
): Provides immediate feedback to the code you write.
Play button
(
5
): Executes code from a selected line.
Border
(
6
): This border separates the Editor and Results areas. If you find the results displayed in the Results area are truncated, drag the border to the left to increase the size of the Results area.
Debug Toggle
(
7
): Shows and hides the Debug area.
Play
/
Stop button
(
8
): Executes or stops the execution of all code in the playground.
You may find the code in the playground a bit too small. Let's see how to change that in the next section.
All programming languages can store numbers, words, and logic conditions, and Swift is no different. Even if you're an experienced programmer, you may find that Swift implements storage for numbers, words, and logic conditions differently from other languages that you might be familiar with. Let's walk through the Swift versions of these simple data types, which are as follows:
Integers
Floating-point numbers
Booleans
Strings
After this, you will also take a look at how to use constants and variables to store these data types in the playground.
Let's say you want to store the following:
The number of restaurants in a city
Passengers in an airplane
Rooms in a hotel
You would use integers, which are numbers with no fractional component.
Integers in Swift are represented by the Int type. Negative numbers are included.
Let's say you want to store the following:
Pi (3.14159...)
Absolute zero (-273.15 °C)
You would use floating-point numbers, which are numbers with a fractional component. The default type for floating-point numbers in Swift is Double, which uses 64 bits, including negative numbers. You can also use Float, which uses 32 bits, but Double is preferred.
Sometimes, you need to store answers to simple yes/no questions, such as the following:
Is it raining?
Are there any available seats at the restaurant?
For this, you use Boolean values. Swift provides a Bool type that can be assigned true or false.
A string is a series of characters. You use strings to store things such as the following:
The name of a restaurant, such as
"Bombay Palace"
A job description, such as
"Accountant"
or
"Programmer"
A kind of fruit, such as
"banana"
Swift strings are represented by the String type, which is fully Unicode-compliant.
Now that you know about Swift's implementation of these common data types, let's use them in the playground we created. Perform the following steps:
Type the following code into the Editor area of your playground and click the Play/Stop button when done:
// Examples of integers 42-23 // Examples of floating-point numbers3.141590.1-273.15 // Examples of booleanstruefalse // Examples of strings"hello, world""albatross"
Note that any word with // in front of it is a comment. Comments are a great way to create notes or reminders to yourself and that will be ignored.
Wait a few seconds. Y
ou should see the values displayed in the Results area.
Cool! You have just created and run your first playground. Let's look at how to store different data types in the next section.