34,79 €
Want to build iOS 12 applications from scratch with the latest Swift 4.2 language and Xcode 10 by your side? Forget sifting through tutorials and blog posts; this book is a direct route to iOS development, taking you through the basics and showing you how to put principles into practice. Take advantage of this developer-friendly guide and start building applications that may just take the App Store by storm!
If you’re already an experienced programmer, you can jump right in and learn the latest iOS 12 features. For beginners, this book starts by introducing you to iOS development as you learn Xcode and Swift. You'll also study advanced iOS design topics, such as gestures and animations, to give your app the edge. You’ll explore the latest Swift 4.2 and iOS 12 developments by incorporating new features, such as the latest in notifications, custom-UI notifications, maps, and the recent additions in Sirikit. The book will guide you in using TestFlight to quickly get to grips with everything you need to get your project on the App Store.
By the end of this book, you'll be ready to start building your own cool iOS applications confidently.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 418
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:Larissa PintoContent Development Editor:Flavian VazTechnical Editor:Akhil NairCopy Editor:Safis EditingProject Coordinator:Kinjal BariProofreader:Safis EditingIndexer:Rekha NairGraphics:Alishon MendonsaProduction Coordinator:Jyoti Chauhan
First published: October 2016 Second edition: October 2017 Third edition: December 2018
Production reference: 1201218
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78934-866-8
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.
Craig Clayton is 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 three 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.
Kevin Munc (@muncman) is a programming veteran with 20+ years' experience in a variety of areas, ranging from mainframes to mobile, from web to blockchain, and from enterprise to startup. Along the way, he's reviewed books on Objective-C, watchOS, RFP, UIAutomation, SpriteKit, JavaFX, and Vim.
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 12 Programming for Beginners Third Edition
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
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
Getting Familiar with Xcode
Getting started
The Xcode interface
Navigator panel
Standard editor
Utilities panel
Debug panel
Toolbar
Generic iOS device
iOS device
Connecting wirelessly
Window pane controls
Summary
Building a Foundation with Swift
Playgrounds – an interactive coding environment
Data types – where it all starts
String
Integer data type
Floating-point numbers
Booleans
Variables and constants – where data is held
Creating a variable with a string
Creating a variable with an integer (int)
Debug and print() – detecting your bugs
Adding floating-point numbers
Creating a Boolean
Why constants versus variables?
Comments – leaving yourself notes or reminders
Type safety and type inference
Concatenating strings
String interpolation
Operations with our integers
Increment and decrement
Comparison operators
Summary
Building on the Swift Foundation
Creating a Playground project
The if statements – having fun with logic statements
Optionals and optional bindings
Why optionals?
Functions
Summary
Digging Deeper
Creating a Playground project
Ranges
Closed range
Half-closed range
Control flow
The for...in loop
One-sided range
The while loop
The repeat...while loop
Summary
Digging into Collections
Arrays
Creating an empty array
Creating an array with initial values
Creating a mutable array
Adding items to an array
Checking the number of elements in an array
Checking for an empty array
Retrieving a value from an array
Iterating over an array
Removing items from an array
Dictionaries
Creating a dictionary
Adding and updating dictionary elements
Accessing an item in a dictionary
Iterating over dictionary values
Iterating over dictionary keys
Iterating over dictionary keys and values
Checking the number of items in a dictionary
Removing items from a dictionary
Sets
Creating an empty set
Creating a set with an array literal
Creating a mutable set
Adding items to a set
Checking whether a set contains an item
Iterating over a set
Intersecting two sets
Joining two sets
Removing items from a set
Summary
Starting the UI Setup
Useful terms
View Controllers
Table View Controllers
Collection View Controllers
Navigation Controllers
Tab Bar Controllers
Storyboards
Segues
Stack Views
Auto Layout
Model View Controller (MVC)
App tour
The Explore tab
Locations
Restaurant listings
Restaurant detail
The Map tab
Project setup
Creating a new project
Summary
Setting Up the Basic Structure
Starting from scratch
Storyboard setup
Adding our app assets
Storyboards
Creating our launch screen
Adding a Navigation Controller
Summary
Building Our App Structure in Storyboard
Adding a Collection View Controller
Hooking up our outlets
Creating a custom color
Setting up our cell
Section header
Updating the grid
Adding a modal
Updating Bar Button Items
Unwinding our Cancel button
Adding our first Table View
Summary
Finishing Up Our App Structure in Storyboard
Adding our Restaurant List View
Hooking up our outlets
Setting up our cell
Adding the Reviews View
Viewing reviews
Map Kit View
Summary
Designing Cells
Setting up the Explore header
Adding Auto Layout to the Explore header
Setting up the Explore cell
Adding Auto Layout to the Explore cell
Setting up the Restaurant cell
Adding Auto Layout to the Restaurant cell
The Locations cell
Summary
Getting Started with the Grid
Understanding the Model View Controller architecture
Getting familiar with the setup
Classes and structures
Controllers and classes
Understanding Collection Views
Creating our controller
Understanding Collection View controllers and Collection View cells
Getting data into Collection View
Understanding the data source
Summary
Getting Data into Our Grid
Model
ExploreData.plist
ExploreItem.swift
ExploreDataManager.swift
Getting data
Connecting to our cell
Hooking up our UI with IBOutlets
Restaurant listing
Summary
Getting Started with the List
Understanding Table Views
Creating our Location View Controller class
Connecting our Table View with our Location View Controller
Digging into our Table View code
Adding the data source and delegate
Adding locations to our Table View
Creating our first property list (plist)
Adding data to our property list
Creating our location data manager
Working with our data manager
Summary
Where Are We?
Setting up map annotations
What is an MKAnnotation?
Creating a restaurant annotation
Creating our Map Data Manager
Creating a base class
Refactoring code
Refactoring ExploreDataManager
Creating and adding annotations
Creating our Map View Controller
Creating custom annotations
Map to restaurant detail
Creating a storyboard reference
Map to restaurant detail
Passing data to restaurant detail
Organizing your code
Refactoring ExploreViewController
Using the MARK comment
Refactoring RestaurantViewController
Refactoring MapViewController
Summary
Working with an API
Creating an API Manager
What is an API?
Understanding a JSON file
Exploring the API Manager file
Location list
Selecting a location
Adding a Header view
Passing a selected location back to Explore View
Unwinding our Done button
Getting the last selected location
Passing location and cuisine to the restaurant list
Creating our restaurant cell class
Setting up restaurant list cell outlets
Creating a restaurant data manager
Handling no data
Summary
Displaying Data in Restaurant Detail
Displaying data in our static Table View
Summary
Foodie Reviews
Getting started with reviews
Displaying ratings in our custom UIControl
Adding our touch events
Setting up the unwind segues
Creating our ReviewFormController
Summary
Working with Photo Filters
Understanding filters
Creating our filter scroller
Creating a filter cell
Creating our PhotoFilterViewController
Getting permission
Summary
Understanding Core Data
What is Core Data?
Creating a data model
Entity autogeneration
The RestaurantPhoto Entity
Review item
Core Data manager
Summary
Saving Reviews
Saving reviews
Saving photos
Adding an overall rating
Summary
Universal
Explore
Location listing
Restaurant listing
Updating the restaurant detail page
Summary
iMessages
Understanding iMessages
Creating our extension
Updating our assets
Creating a framework
Connecting your message cell
Showing restaurants
iMessage crashing
Sending reservations
Summary
Notifications
Starting with the basics
Getting permission
Setting up notifications
Showing notifications
Customizing our notifications
Deliver quietly (iOS 12 feature)
Embedding images (iOS 10 feature)
Adding buttons
Grouped notifications (iOS 11)
Summary and hidden text (iOS 12)
Custom UI in notifications
Custom Notification Settings (iOS 12)
Summary
SiriKit
Using Siri Shortcuts
Siri voice shortcut
Understanding SiriKit
Supported intents
Enabling Siri's capabilities
Creating users
Updating our intent handler
Testing Siri
Summary
Beta and Store Submission
Creating a bundle identifier
Creating a certificate signing request
Creating production and development certificates
Creating a production provisioning profile
Creating a development provisioning profile
Creating an App Store listing
Creating an archive build
Internal and external testing
Internal testing
External testing
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
In this book, we will build a restaurant reservation app called Let's Eat. We will start the book off by exploring Xcode, our programming environment, which is also known as the Interface Development Environment (IDE). Next, you will start learning the foundations of Swift, the programming language used in iOS apps. Once we are comfortable with the basics of Swift, we will dig deeper to build a more solid foundation.
Once we have a solid foundation of using Swift, we will start creating the visual aspects of our Let's Eat app. During this process, we will work with storyboards and connect our app's structure together using segues. With our UI complete, we will go over the different ways in which we can display data. To display our data in a grid, we will use Collection Views, and to display our data in a list, we will use Table Views.
We will also look at how to add basic and custom annotations on to a map. Finally, it's time to get real data; we will look at what an Application Programming Interface (API) is and how we can get actual restaurant data into our Collection Views, Table Views, and Map.
We now have a complete app, but how about adding some bells and whistles? The first place where we can add a feature will be the restaurant detail page, where we 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. When they are done, we will save this data using Core Data.
Since we built our app to work on both iPhone and iPad, we should add the ability to make our app support iPad multitasking. Doing this will allow our app to be open alongside another app at the same time.
If we want to be able to send our reservation to a friend, we can create a custom UI for iMessages, which will send them the details for the reservation along with the app it came from. The one thing missing from our app is the ability to notify the user with a custom notification to alert when they have an upcoming reservation.
Finally, let's create quick access by using SiriKit and Siri to request money and send reservations. Now that we have added some bells and whistles, let's get this app to our friends using TestFlight, and finally get it into the App Store.
This book is for you if you are 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 12 features.
Chapter 1, Getting Familiar with Xcode, takes you through a tour of Xcode and talks about all the different panels that we will use throughout the book.
Chapter 2, Building a Foundation with Swift, deals with the basics of Swift.
Chapter 3, Building on the Swift Foundation, teaches us to build on our Swift foundation and learn some further basics of Swift.
Chapter 4, Digging Deeper into Swift, talks about ranges and control flow.
Chapter 5, Digging into Swift Collections, talks about the different types of collections.
Chapter 6, Starting the UI Setup, is about building the Let's Eat app. We will focus on getting our structure set up using storyboards.
Chapter 7, Setting Up the Basic Structure, deals with working on our Let's Eat app in a storyboard.
Chapter 8, Building Our App Structure in Storyboard, is about adding more to our app structure in a storyboard.
Chapter 9, Finishing Up Our App Structure in Storyboard, concludes the discussion of our app structure in a storyboard.
Chapter 10, Designing Cells, is about designing the table and collection view cells in a storyboard.
Chapter 11, Getting Started with the Grid, concerns working with Collection Views and how we can use them to display a grid of items.
Chapter 12, Getting Data into Our Grid, concerns the incorporation of data into our Collection Views.
Chapter 13, Getting Started with the List, teaches us to work with Table Views and takes an in-depth look at dynamic Table Views.
Chapter 14, Where Are We?, deals with working with MapKit and learning how to add annotations to a map. We will also create custom annotations for our map.
Chapter 15, Working with an API, involves learning how to use a JSON API within our app.
Chapter 16, Displaying Data in Restaurant Detail, teaches you how to pass data using segues.
Chapter 17, Foodie Reviews, talks about working with the phone's camera and library.
Chapter 18, Working with Photo Filters, takes a look at how to apply filters to our photos.
Chapter 19, Understanding Core Data, teaches us the basics of using core data.
Chapter 20, Saving Reviews, wraps up reviews by saving them using core data.
Chapter 21, Universal, deals with multitasking on the iPad, and how we can get an update to be supported on all devices.
Chapter 22, iMessages, is about building a custom message app UI. We will also create a framework to share data between both apps.
Chapter 23, Notifications, provides instruction on how to build basic notifications. Then, we will look at embedding images into our notifications as well as building a custom UI.
Chapter 24, SiriKit, teaches the reader how to use Siri to create money requests.
Chapter 25, Beta and Store Submission, concerns how to submit apps for testing as well as submitting apps to the App Store.
You need to have Xcode 9 installed on your system. To download Xcode 9, visit https://developer.apple.com/xcode/.
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 athttps://github.com/PacktPublishing/iOS-12-Programming-for-Beginners-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 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://www.packtpub.com/sites/default/files/downloads/9781789348668_ColorImages.pdf.
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: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
states.insert("Ohio", at:1) states.insert(contentsOf:["North Carolina", "South Carolina", "Nevada"],at:3)
Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Hit Next and then Create."
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.
So, you want to get into iOS development? I was in your shoes on January 27, 2010, when Apple first announced the iPad. As soon as the conference was over, I knew that I wanted to learn how to create apps for the iPad. I signed up for the Apple Developer website and paid my $99 annual fee. But then, I realized that I did not know where to begin. A large variety of instructional books or videos did not exist, especially since the iPad hadn't released. I had previous programming experience; however, I had no idea how to write Objective-C (the original programming language for iOS). Therefore, I had to teach myself the basics. In this book, we will learn what it takes to become an iOS developer together.
If you are new to programming, take your time. You should understand the lessons that are provided in one chapter before moving on to the next. These essential skills will set you up with a solid foundation in iOS development. If you have previous programming experience, you should still review the earlier chapters, as they will be a refresher for you.
Throughout this book, we will work in Xcode, specifically Xcode 10 (and Swift 4, which we will tackle later in this book). Xcode is known as an Integrated Development Environment (IDE). Using Xcode gives us everything we will need to build apps for iOS, tvOS, macOS (formerly, OS X), and watchOS. In this chapter, we will explore Xcode to help you get more comfortable using it. If you are not on Xcode 10, make sure to update Xcode, as the code in this book will not run correctly otherwise.
Our focus in this book will be on creating a universal iOS app (an app for both the iPhone and iPad). The best way to do this is to create a project to familiarize yourself with where everything is and how to find what you need. So first, let's first download and install Xcode.
To download Xcode, launch the App Store on your Mac and then type Xcode into the search bar in the upper-right corner:
Next, click on INSTALL:
Once installed, launch Xcode, and you should see the following Welcome to Xcode screen:
If this is the first time you have launched Xcode, then you will see No Recent Projects in the right-hand panel. If you have previously created projects, then you will see those listed to the right. To get started, we are going to click on Create a new Xcode project in the left-hand panel of the welcome screen. 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. Since we are creating apps for iOS, make sure that you have iOS selected. Then, choose Single View App and click on Next. Now, you will see an options screen for a new project:
This option screen has the following seven items to complete or choose:
Product
Name
: The product name is your app. We are going to set ours as
ExploringXcode
.
Team
: The team connects to your Apple account. We are going to ignore this for now, because we do not need the Team for this chapter. If you already have a team set up, leave it as is. We will cover this in greater detail later in this book.
Organization Name
: You can set the organization name to your company name, or just use your name.
Organizer I
dentifier
: You will set the organizer identifier to be your domain name in reverse. For example, my website URL is
cocoa.academy
, and therefore, my identifier is
academy.cocoa
. Since URLs are unique, it will ensure that no one else will have your identifier. If you do not have a domain, then use your first and last names for now. However, you will eventually have to purchase a domain if you want to submit your app to the Apple Store.
Bundle I
dentifier
: When you create a new project, Apple will combine your
Product Name
with your
Organizer Identifier
to create your unique bundle identifier. So, even if 10,000 people create this project, each person will have a different bundle identifier.
Language
: Set language to
Swift
.
Checkboxes
: You can uncheck
Use Core Data
,
Include Unit Tests
, and
Include UI Tests
, as these are things that we will not use in this chapter.
Now, select Next, and Xcode will prompt us to save our project. I have a dedicated folder for all my projects, but you can save it on your desktop for easy access.
Your project is now open, and it is time for us to get familiar with all of the panels. If this is your first time in Xcode, then it will probably be a bit overwhelming for you. Therefore, we will break it down into six parts:
The primary use of the navigator panel is to add new files and select existing files. The other icons are used from time to time; we will cover them as we need them.
The standard editor is a single panel view that's used to edit files. The standard editor area is the primary area in which you will work. In this area, we can view storyboard files, see our Swift files, or view our project settings.
The utilities panel can be a bit confusing when you first use Xcode because this menu changes based on what you have selected in the standard editor. When we start building an app, we will dig deeper into this. For now, know that the utilities panel is made up of the inspector pane at the top and the library pane at the bottom. The inspector pane allows you to change the attributes or properties of things you put in your storyboard; the library pane enables you to insert objects, image assets, and code snippets into your app.
The debug panel will allow us to see log messages from our app. You will become very familiar with this panel by the time you finish this book. The debug panel is one of the most excellent tools for getting feedback on what your app is doing or not doing.
Next, we look at the toolbar, which is demonstrated as follows:
First, we have a play button, which is how we launch our app (or use command + R). Next, you will see a stop button, which will not be active until you run your app. This stop button (or command + .) is used to stop your app from running. To the right of the stop button, you will see your target (your project name), along with the current simulator that has been selected. If you click on your project name, you will see a screen similar to this:
This drop-down menu, which we will call the Device and iOS Simulators drop-down menu, allows you to change your simulator type. For our project, select iPhone7 Plus as your simulator and then click on the play icon (or use command + R) to run your app.
Now, let's return to Xcode and select the stop button (or use command + .).
If you use the keyboard shortcut, make sure Xcode is in focus; otherwise, this shortcut will not work. I work on a 15-inch MacBook Pro Retina. Therefore, when I am working on an app, I will use the iPhone X or iPad Air 2 simulator in landscape mode. They both fit nicely on my screen without me having to resize either.
In addition to the Simulator, there is a Build Only Device as well as a Device section, both of which can be found at the top of the Device and Simulator drop-down menu that was shown earlier in this chapter. Note that, for our purposes, you will only need a simulator while we are building the app; however, you can add an iOS device if you would like (see under iOS Device).
The Generic iOS Device, under the Build Only Device section of the Device and Simulator drop-down menu, is used for when you need to archive your app, which means that you are preparing your app for submission to Apple (either to the App Store or Test Flight). If you try to select Generic iOS Device now and run the app, you will get the following message:
Therefore, change Generic iOS Device to an actual simulator, and then you will be able to continue.
If you do not have a device connected to the computer, you will see No devices connected under the Device section of the Device and Simulator drop-down menu.
As noted earlier, when we start building the Let's Eat app, you will have the option of using the simulator or connecting a device to Xcode. Using a device is slower; however, the simulator will not perform in the same way as a device will.
In the past, you needed to have a paid account to build your app on a device. Nowadays, you do not need a developer account to run the app on your device. Note that, if you decide to connect your device instead of using a simulator, you will need iOS 12 installed on it. Xcode 10 introduced the capability of connecting your phone wirelessly. We will look at the traditional way first and then we will go over how you can connect your phone wirelessly.
The following steps are only intended for those of you who do not want to pay for the Apple Developer Program at this time:
Connect your iOS device via USB.
In the drop-down menu, select your device (here, I have chosen
Xclusive iPhone 6 Plus
):
Wait for Xcode
10
to finish indexing and processing. The indexing and processing may take a bit of time. Once complete, the status will say
Ready
.
Run the project by hitting the Play button (or use
command
+
R
).
You will get two errors that state the following:
Signing for
ExploringXcode
requires a development team. Select a development team in the project editor.
Code signing requires a product type application in SDK iOS 12.0.
Ignore the specifics of these errors as they indicate that we need to create an account and add our device to that account.
Now, in the standard editor, you will see under
Signing
that you need to add an account:
Click on
Add Account
. If a
Sign into Xcode with your Apple ID
dialog box does not pop up, inside the
Accounts
screen on the bottom left, click on the
+
and select
Apple ID
:
Then, when you click on
Create Apple ID
, you will be asked to enter your birth date, name, email, and password, along with a number of security questions. Make sure that you verify your email before you answer the security questions, otherwise you will have to come back to this screen and add your
Apple ID
again.
Once you have finished all of the steps, you will see your account, as follows:
If you already have an account, then instead of seeing Add Account, you will see a drop-down menu with your account listed. If your device is not connected to this account, you might see a message asking if you would like to add your device to your account. Adding your device to an account is for testing purposes only.
Now that you have your phone and account connected, you can quickly get your phone set up to run wirelessly. With your device already connected via USB, go to Window | Devices, and then Simulators. Click on the checkbox marked Connect via network:
Make sure that your phone and your computer are connected to the same Wi-Fi network.
When I first connected to my device, I saw a globe icon in Xcode that lets you know that your device is connected via the network, as demonstrated in the following screenshot:
After a short time, the globe went away. Even if you do not see the icon, you can disconnect the USB, and your device should still be connected to Xcode (as long as it is connected to the same Wi-Fi network).
You will not need to use a device for this book, but it is always good to run your app in an actual device before you submit it to the store.
Before we get to the right-hand side of the toolbar, select the Main.storyboard file in your navigator panel. This file is used to display all of your visual setup for your entire app. We will this in detail later in this book. After you select the file, you should see the following:
The following screenshot shows the window pane controls:
Moving on to the window pane controls, you will see two groups of icons. The first group is called the Editor Mode, and the second group is called the View. Let's look at the functions of the Editor Mode icons:
Editor Mode icons
Function
This icon controls the standard editor (which is the center panel in the earlier screenshot of the
Main.storyboard
file in the navigator panel).
This icon splits the Standard editor into two panels, where you will see the
ViewController.swift
file on the right. We will use this split screen throughout this book.
This icon is the Version editor. We will not address the Version editor in this book since it is a more advanced feature.
At this point, you might be thinking that there are way too many panels open, and I would agree with you! The last panel is where the previous group of View icons in the toolbar comes in handy.
Let's look at these icons and their functions in the following table:
View Mode icons
Function
This icon will toggle (hide or show) the navigator panel (or use
command
+
O
).
This icon will toggle (hide or show) the debug panel (or use command + shift + Y).
This icon will toggle (hide or show) the utilities panel (or use command + alt + O).
Congratulations! You have finished exploring the basics of Xcode. When we start building our app, we will cover the more essential parts of Xcode in depth. In the next few chapters, we will begin learning about the Swift programming language. We will use the latest Swift version, and this will be a basic intro into the programming language. If you are familiar with Swift, feel free to skip ahead to Chapter 6, Starting the UI Setup. Even if you are familiar with Swift, it is always good to go back through the basics as a refresher. So, let's get started!
Now that we have had a short tour of Xcode, it is time to start learning about Swift. Remember, if you are new to programming, things will be very different for you, so take your time. The essential skills that you learn here will set you up with a solid foundation in iOS development. If you have previous programming experience, you should still review this chapter, as it can only enhance your programming skills and act as a refresher for you.
On June 2, 2014, Apple changed the game for iOS development, because this was the day they announced Swift to the world. With this announcement, everybody was put on an even playing field, because they had to learn a new programming language. Swift has brought a more modern approach to developing apps and has seen a massive influx of new developers of all ages wanting to build iOS apps. However, enough about history! Let's dig in and look at what you are going to learn about.
The following topics will be covered in this chapter:
Playgrounds
Data types
Variables and constants
Debug and
print()
Comments
Before we jump into building the app that we will be creating in later chapters, called Let's Eat, we need to understand the basics of Swift. An easy way to experiment with Swift is to use Playgrounds. It is an interactive coding environment that evaluates your code and displays the results. Using Playgrounds gives us the ability to work with Swift without needing to create a project. It is great for prototyping a particular part of your app. So, whether you are learning or experimenting, Playgrounds are an invaluable tool. To create a Playground, we need to launch Xcode and click on Get started with a playground:
The Playground template screen appears. Make sure that you select iOS, and then choose Blank and hit Next:
You will be asked to give your project a name and a location to save the file; name your new project Playground iOS11-Programming-for-Beginners-Ch2. You can save the file anywhere that you like. Now, with the project saved, we can explore Playgrounds in a little more detail.
When you launch the app, you will see five distinct areas:
Let's break down each area in Playgrounds:
Playground Editor
: This area is where you write all of your code.
Results Panel
: The Results panel is a feature that's only found in Playgrounds and provides immediate feedback.
Window Pane Controls
: The Window Pane Controls have two groups of icons:
As we discussed earlier, the first group is called the Editor Mode, and the second group is called the View. Refer to the detailed description of these icons in the previous chapter for information about what each one does.
Debug Toggle
: This button allows you to hide and show the Debug panel and toggle on the Debug panel.
Play/Stop
: This button is used to make Playgrounds execute code or to stop Playgrounds from running. Typically, Playgrounds runs on its own, but sometimes you need to manually toggle this feature on when Playgrounds does not execute your code for you.
Now that we have the Xcode panels setup, delete all of the code in this file. Your Playground should have three open panels: your Playground Editor, the Results Panel, and the Debug Panel. Let's start digging into some code.
Swift offers a collection of built-in data types. Its data types are a string, an integer, floating-point numbers, and Booleans. These data types are found in most programming languages. Therefore, if you are not new to programming, you can skip this section and start at the Variables and constants – where data is held section later.
Let's walk through each data type for those of you who are new to programming or would like a refresher.
The first data type we will cover is a string. A series of characters represent a string. Strings are used to display text in an app. A string wrapped in quotes is known as a string literal. In programming, we cannot just add text to Playgrounds. So, to write a string, we must wrap our string inside quotes.
Let's add our name into Playgrounds, wrapped in quotes:
In Playgrounds, your values appear inside of your Results Panel. So, we now know that in order to create a string, we need to use quotes.
Integers (Ints) are whole numbers, such as 32 and −100. Integers are useful when you need to perform calculations (that is, adding, subtracting, multiplication, and so on). Let's add some numbers to Playgrounds. On the next line, under your name, type 32, and then, on the following line, −100, as demonstrated in the following screenshot:
Again, you see both 32 and −100 in the Results Panel under your name.
Floating-point numbers are numbers with a fractional component, such as 4.993, 0.5, and −234.99. Let's add these values to Playgrounds as well:
Booleans (bools) are referred to as logical because they can either be true or false. Use Booleans when you need to determine whether some logic is true or false. For example, did the user log in? This statement would either be true—yes they did, or false—no they did not. So, in Playgrounds, add true and false:
Now, we have covered all of the primary data types in Swift. Right now, we have no way to use these data types. Using the data is where variables and constants come into play.
Variables and constants are like containers that contain any data. When you want to declare a variable, you have to use the var keyword. Let's declare each of the data types we did earlier, but, this time, using variables and constants instead.
We can use the Debug panel (at the bottom of the following screenshot) using print(). So, let's see how print() works by printing both our name and age. We can do this by adding the following:
print(fullName)print(age)
It should appear on your screen as follows:
You should now see the output in both the Results and Debug Panels. Using print() allows us to see things in our Debug Panel and therefore verify expected results. Using print() is a handy debugging tool.
You might be asking yourself "Why would you ever want to make something constant?". Since constants cannot change after you run your app, they keep you from accidentally breaking a value that should not change. Another excellent use for constants is for base URLs, as you would not want these to change. When you are getting data, you do not want to change the value midway through your app accidentally. Apple recommends that you use let whenever possible. Typically, I use let until Xcode warns me that a var is preferable. If I change the value from let to var, then I am verifying that this is the behavior I want.
Comments are a great way to create notes or reminders to yourself. When you comment code, it means that it will not execute when your code runs. There are two types of comment used: // or /* */. // is used for a one-line comment and /**/ is used for a block of text.
Let's see what both of these look like:
Swift is a type-safe language, which means that you are encouraged to be clear about the value types with which your code works. Type inference means that, before your code runs, it quickly checks to ensure that you did not set anything to a different type. If you do, Xcode gives you an error. Why is this good? Let's say that you have an app in the store and that you set one of your variables as a String in one part of your code, but then accidentally set the same variable as an Int