iOS 10 Programming for Beginners - Craig Clayton - E-Book

iOS 10 Programming for Beginners E-Book

Craig Clayton

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

You want to build iOS applications for iPhone and iPad—but where do you start? Forget sifting through tutorials and blog posts, this is a direct route into iOS development, taking you through the basics and showing you how to put the principles into practice. With every update, iOS has become more and more developer-friendly, so take advantage of it and begin building applications that might just take the App Store by storm!

Whether you’re an experienced programmer or a complete novice, this book guides you through every facet of iOS development. From Xcode and Swift—the building blocks of modern Apple development—and Playgrounds for beginners, one of the most popular features of the iOS development experience, you’ll quickly gain a solid foundation to begin venturing deeper into your development journey. For the experienced programmer, jump right in and learn the latest iOS 10 features.

You’ll also learn the core elements of iOS design, from tables to tab bars, as well as more advanced topics such as gestures and animations that can give your app the edge. Find out how to manage databases, as well as integrating standard elements such as photos, GPS into your app. With further guidance on beta testing with TestFlight, you’ll quickly learn everything you need to get your project on the App Store!

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 445

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

iOS 10 Programming for Beginners
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading theexample code
Downloading the color images of this book
Errata
Piracy
Questions
1. Getting Familiar with Xcode
Getting started
The Xcode interface
Navigator panel
Standard editor
Utilities panel
Debug panel
Toolbar
Generic iOS Device
iOS device
Window Pane Controls
Summary
2. 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
Hungarian notation
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
If-Statements – having fun with logic statements
Optionals and Optional Bindings
Why optionals?
Functions
Let's Work
Summary
3. Digging Deeper
Creating a Playground project
Ranges
Closed Range
Half closed Range
Control flow
The for…in loop
The while loop
The repeat…while loop
Summary
4. 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 into a set
Checking if a set contains an item
Iterating over a set
Intersecting two sets
Joining two sets
Removing items from a Set
Summary
5. Starting the UI Setup
Useful terms
View Controller
Table View Controller
Collection View Controller
Navigation Controller
Tab Bar Controller
Storyboard
Segue
Auto layout
Model View Controller (MVC)
App Tour
Explore tab
Locations
Restaurant listings
Restaurant detail
Map tab
Project setup
Creating a new project
Creating our files
Storyboard setup
Adding our App assets
Storyboards
Creating our launch screen
Adding a Navigation Controller
Creating a custom title view
Adding a container
Using Stack Views
Adding a Custom Label and an Arrow to Our Custom Title View
Summary
6. Setting Up UI
Design clean up
Adding a Clear Background to the Custom Title View
Updating the UIStackView
Updating our Arrow
Updating our Label
Adding a Button
Collection View
Adding a Modal
Map Kit View
Fixing the Crash
Refactoring the Storyboard
Creating a New Storyboard for the Explore Tab
Creating a New Storyboard for the Map Tab
Folder Setup
Organizing folders
Setting up Global Settings
Breaking Down our App Delegate
Summary
7. Getting Started with the Grid
Understanding the Model View Controller architecture
Model
View
Controller
Getting familiar with the setup
Classes and Structures
Controllers and Classes
Creating our Controller
Understanding Collection View Controllers and Collection View Cells
Getting Data into Collection View
Understanding the Data Source
Updating the Grid
Model
ExploreData.plist
ExploreItem.swift
ExploreDataManager.Swift
Getting Data
CollectionView Cell
Connecting to Our Cell
Hooking up Our UI with IBOutlets
Cell Selection
Restaurant Listing
Summary
8. Getting Started with the List
Updating UI in Storyboard
Updating Bar Button Items
Unwinding our cancel button
Adding Our First Table View
Updating Our Edges
Creating Our View Controller Class
Connecting our TableView with our Location View Controller
Adding the Data Source and Delegate
Creating a Prototype Cell
Digging into Our Table View code
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
9. Working More with Lists
Creating our Restaurant detail
Setting up our static Table View
Exploring Restaurant details
Creating our section headers
Adding our labels
Address section
Creating Reviews
Reservations
Adding reservation times
Reservation information
Reservation header
Summary
10. 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 ExploreDataManager
Creating and adding annotations
Creating our Map View Controller
Creating custom annotations
Refactoring restaurant detail
Creating a Storyboard reference
Map to restaurant detail
Passing data to Restaurant detail
Organizing your code
Summary
11. Where's My Data?
Creating an API Manager
What is an API?
Understanding a JSON file
Exploring the API Manager file
Location list
Selecting a location
Passing a selected location back to Explore View
Getting the last selected location
Passing location and cuisine to the restaurant list
Building our restaurant list
Updating our background
Updating our restaurant list cell
Positioning elements in our restaurant list cell
Adding auto layout to our restaurant list cell
Creating our restaurant cell class
Setting up restaurant list cell outlets
Creating RestaurantDataManager
Displaying data in Restaurant list cell
Restaurant details
Displaying data in the Restaurant Detail view
Passing data to our Restaurant List View Controller
Map update
Challenge yourself
Summary
12. Foodie Reviews
Getting started with reviews
Setting up our table view controllers
Creating reviews
Setting up the Review Storyboard
Updating the Review Cells
Positioning UI elements
Adding Auto Layout for creating reviews
Adding Ratings View
Adding Auto Layout for Ratings View
Adding our Photo Filter View
Adding Auto Layout for the Photo Filter View
Presenting our Views as Modals
Setting up our unwind segues
Hooking up our unwind segues
Working with filters
Creating our Filter Scroller
Creating our apply Filter View Controller
Creating review images
Summary
13. Saving Reviews
What is Core Data?
NSManagedObjectModel
NSManagedObjectContext
NSPersistentStoreCoordinator
Creating a data model
Entity auto-generation
Review item
Core Data Manager
Creating star ratings
Setting up the cell UI
Adding Auto Layout
Adding Review List extension
Summary
14. Universal
Explore
Restaurant listing
Updating restaurant details
Updating the header layout
Updating the table details section layout
Updating the No Reviews Layout
Updating the Reviews layout
Updating the Map section layout
Summary
15. iMessages
Understanding iMessages
Creating our extension
Updating our assets
Implementing our Messages UI
Adding Auto Layout to our cell
Creating a framework
Connecting our message cell
Showing restaurants
Sending reservations
Summary
16. Notifications
Starting with the basics
Getting permission
Setting up notifications
Showing notifications
Customizing our notifications
Embedding images
Adding buttons
Custom UI in notifications
Summary
17. Just a Peek
Adding 3D Touch quick actions
Adding favorites
Creating a new model object
Updating our Core Data manager
Summary
18. 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 the App Store Listing
Creating an archive build
Internal and External Testing
Internal testing
External testing
Summary
Index

iOS 10 Programming for Beginners

iOS 10 Programming for Beginners

Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

First published: December 2016

Production reference: 1191216

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78646-450-7

www.packtpub.com

Credits

Author

Craig Clayton

Reviewer

Fernando Rodríguez

Commissioning Editor

Ashwin Nair

Acquisition Editor

Reshma Raman

Content Development Editor

Divij Kotian

Technical Editor

Gebin George

Copy Editor

Charlotte Carneiro

Project Coordinator

Sheejal Shah

Proofreader

Safis Editing

Indexer

Tejal Daruwale Soni

Graphics

Jason Monteiro

Production Coordinator

Melwyn Dsa

About the Author

Craig Clayton is a self-taught, Senior iOS Engineer at Adept Mobile, which specializes in building mobile experiences primarily for NBA and NFL teams. He also volunteers as the organizer of the Suncoast iOS meetup group in the Tampa/St. Petersburg area, and prepares presentations and hands-on talks for the group as well as for other groups in the community.

He has worked with both adults and kids who wish to start learning how to program, or those who aspire to become iOS developers. On top of all that, starting in 2017 Craig has plans to launch Cocoa Academy online, which will specialize in bringing a diverse list of iOS courses. The courses will range from building apps to games for all programming levels.

I would like to thank my friends and family for their support, especially my mom, Corliss Smith. I hope that one day I will get to be there for you when you write your book. I would also like to thank Kim Smallman; you were amazing with your help and guidance in every step of the way. Since you are not a programmer, I really appreciated getting your feedback on things that beginners might not fully understand.

About the Reviewer

Fernando Rodríguez has more than 20 years of experience in developing and teaching other developers. Although currently specialized in the Apple stack of tools, he's a nerd of all trades with a strong interest in Big Data and automated trading.

Fernando has taught iOS development at the Big Nerd Ranch, Udacity, and Keep coding, ranging from Facebook developers to indie devs.

He was awarded for being an outstanding instructor at Udemy for his intro course to iOS development. This course was mentioned in the Financial Times, Venture beat, and Information Week.

I'd like to thank Sheejal Shah from Packt for her patience and Craig Clayton for his hard work.

www.PacktPub.com

eBooks, discount offers, and more

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.PacktPub.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.PacktPub.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.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer Feedback

Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously – that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn.

You can also review for us on a regular basis by joining our reviewers club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us:<[email protected]>.

Preface

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 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.

After 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 apps structure together using segues. With our UI complete, we will go over the different ways that 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 real restaurant data into our Collection Views, Table Views, and Map.

We now have a complete app, but what about adding some bells and whistles? The first place we can add a feature will be on 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 on 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, that 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 some quick access for our app using 3D touch, where by tapping our app icon, the user can quickly jump to their 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.

What this book covers

Chapter 1, Getting Familiar with Xcode, will take us through a tour of Xcode and talk about all of the different panels we will use throughout the book.

Chapter 2, Building a Foundation with Swift, deals with the basics of Swift.

Chapter 3, Digging Deeper, teaches us to build on our Swift foundation and learn some more basics of Swift.

Chapter 4, Digging into Collections, will talk about the different types of Collections.

Chapter 5, Starting the UI Setup, is about building the Let's Eat app. We will focus on getting our structure setup using storyboards.

Chapter 6, Setting Up UI, deals with working on our Let's Eat app in a storyboard.

Chapter 7, Getting Started with the Grid, is about working with Collection Views and how we can use them to display a grid of items.

Chapter 8, Getting Started with the List, teaches us to work with Table View and takes a deep look at dynamic Table Views.

Chapter 9, Working More with Lists, will talk about working with Table Views, but we will look at static Table Views.

Chapter 10, 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 11, Where's My Data?, is about learning how to use a JSON API within our app.

Chapter 12, Foodie Reviews, talks about working with the phone's camera and library. We will then look at how to apply filters to our photos.

Chapter 13, Saving Reviews, wraps up Reviews by saving them using Core Data.

Chapter 14, Universal, deals with multitasking on the iPad, and how we can get an update to be supported on all devices.

Chapter 15, iMessages, is about building a custom message app UI. We will also create a framework to share data between both apps.

Chapter 16, Notifications, provides learning on how to build basic notifications. Then, we will look at embedding images into our notifications as well as building a custom UI.

Chapter 17, Just a Peek, looks at 3D touch and how to add quick actions to our app. We will also look at how we can add peek and pop to our restaurant list.

Chapter 18, Beta and Store Submission, is about how to submit apps for testing as well as submitting apps to the App Store.

What you need for this book

You will need a computer that runs Xcode 8 or greater.

Who this book is for

This book is for beginners who want to be able to create iOS applications. If you have some programming experience, this book is a great way to get a full understanding of how to create an iOS application from scratch and submit it to the App Store. You do not need any knowledge of Swift or any prior programming experience.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading theexample code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enterthe name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on theCode Filesbutton on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged into your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/iOS-10-Programming-for-Beginners.We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/iOS10ProgrammingforBeginners_ColoredImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Getting Familiar with Xcode

So, you want to get into iOS development? I was in your shoes on January 27th, 2010, when Apple first announced the iPad. Literally as soon as the conference was over, I knew that I wanted to learn how to create apps for the iPad. I signed up on 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 had not yet been 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 together what it takes to become an iOS developer.

If you are new to programming, take your time. You should understand the lessons in one chapter before moving on to the next chapter. These important 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 8 (and Swift 3, which we will tackle later in the book). Xcode is known as an Integrated Development Environment (IDE). Using Xcode gives us everything we will need in order to build apps for iOS, tvOS, macOS (formerly, OS X), and watchOS. In this chapter, we will explore Xcode in order to help you get more comfortable using it. If you are not on Xcode 8, make sure to update Xcode, as the code in this book will not run properly otherwise.

Our focus in this book will be to create 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, let's first download and install Xcode.

Getting started

In order 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 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 panel of the welcome screen. This will take us to the new project screen:

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, select Single View Application and click on Next. Now, you will see an options screen for a new project:

This option screen has the following eight items to complete or choose:

Product Name: The product name is your app. We are going to set ours as ExploringXcode.Team: The team is connected to your Apple account. We are going to ignore this for now, because it is not needed for this chapter. If you have a team set up, just leave it as is. We will cover this in greater detail later in the book.Organization Name: You can set the organization name to your company name or just your name.Organizer Identifier: 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 just use your first and last name for now. You will eventually have to purchase a domain if you would like to submit your app to the Apple store.Bundle Identifier: 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: Make sure your language is set to Swift.Devices: We are going to set this as Universal (iPhone and iPad).Checkboxes: You can uncheck Use Core Data, Include Unit Tests, and Include UI Tests, as these are things we will not be using 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.

The Xcode interface

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 probably will be a bit overwhelming for you. Therefore, we will break it down into five parts:

NAVIGATOR PANELSTANDARD EDITORUTILITIES PANELDEBUG PANELTOOLBARWINDOW PANE CONTROLS

Navigator panel

The primary use for the Navigator panel is to add new files and/or select existing files. The other icons are used from time to time, which we will cover as we need them.

Standard editor

The Standard editor is a single panel view 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.

Utilities panel

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, just 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 attributes or properties of things you put in your Storyboard—the library pane allows you to insert objects, image assets, and code snippets into your app.

Debug panel

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 greatest tools to get feedback on what your app is doing or not doing.

Toolbar

Next, we look at the Toolbar:

First, we have a Play button, which is how we launch our app (or use Cmd + R). Next, you will see a Stop button, which will not be active until you run your app. This Stop button (or Cmd + .) 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 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 Simulator drop-down menu, allows you to change your simulator type. For the purposes of our project, select iPhone 7 Plus as your simulator and then click on the play icon (or use Cmd + R) to run your app. Your app will be blank and most likely will not fit the entire screen (unless you are on a large screen).

In order to see the entire screen, you can scroll right and left—however, doing this gets harder once you have elements in your app. So, an alternative to scrolling is to resize your app to fit the screen. We can do this by going to your Simulator menu and navigating to Window | Scale:

Here, you will be able to scale from 100% to 75%, 50%, 33%, or 25% (select whichever percentage allows the app to best fit your screen size).

Now, let's return to Xcode and select the Stop button (or use Cmd + .).

Tip

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 6 or iPad Air 2 simulator in landscape. They both fit nicely on my screen without having to resize either.

In addition to the simulator, there is a Build Only Device as well as a Device section, both 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).

Generic 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 to Test Flight). If you try to select Generic iOS Device now and run the app, you will get the following message:

Therefore, changeGeneric iOS Device to an actual Simulator, and then you will be able to continue.

iOS device

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 the same as a device will.

In the past you, you needed to have a paid account to build your app on a device. Now, you do not need a developer account in order 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 10 installed on it. The following steps are only for those 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, Craig's iPhone):Wait for Xcode 8 to finish indexing and processing. This may take a bit of time. Once complete, the status will say Ready.Run the project by hitting the Play button (or use Cmd + 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 is required for product type Application in SDK iOS 10.0.

Ignore the specifics of these errors as they basically 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 in to Xcode with your Apple ID dialog box does not pop up, inside of the Accounts screen on the bottom left, click on the + and select Add Apple ID:Then, you will click on Create Apple ID. You will be asked to enter your birth date, name, e-mail, and password, along with security questions. Make sure that you verify your e-mail before you answer the security questions; otherwise, you will have to come back to this screen and add Apple ID again.Once you have finished all the steps, you will see your account:

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.

You will not need to use a device for the majority of this book—however, depending on the type of Macbook you have, you might need to use a device.

Before we get to the right side of the Toolbar, select the Main.storyboard file in your Navigator panel. This file is used to do all of your visual setup for your entire app. We will cover this in detail later in the book. After you select the file, you should see the following:

Window Pane Controls

The following screenshot shows Window Pane Controls:

Tip

For better quality of images, download the Graphics bundle from : https://www.packtpub.com/sites/default/files/downloads/iOS10ProgrammingforBeginners_ColoredImages.pdf

Moving onto 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 the 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. This is where the last 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

Functions

This icon will toggle (hide or show) the Navigator panel (or use Cmd + 0).

This icon will toggle (hide or show) the Debug panel (or use Cmd + Shift + Y).

This icon will toggle (hide or show) the Utilities panel (or use Cmd + Alt + 0).

Summary

Congratulations! You have finished exploring the basics of Xcode. When we start building our app, we will cover the more important parts of Xcode in depth. It is now time to start learning Swift 3.

Chapter 2. Building a Foundation with Swift

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 important skills that you will 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 Swift was announced 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 huge influx of new developers of all ages wanting to build iOS apps. But, enough about history! Let's dig in and see what you are going to learn.

The following will be covered in this chapter:

PlaygroundsData typesVariables and constantsDebug and print()CommentsType safety and type inferenceif statementsOptionals and optional bindingsFunctions

Playgrounds – an interactive coding environment

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, which 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 is an invaluable tool. In order to create a Playground, we need to launch Xcode and click on Get started with a playground:

The options screen for creating a new Playground screen will appear:

First, name your new Playground SwiftFoundation, and then make sure your Platform is set to iOS. Now, we can explore Playgrounds a bit.

When you launch the app, you will see five distinct areas:

Let's breakdown each area in Playgrounds:

PLAYGROUND EDITOR: This area is where you will write all of your code.RESULTS PANEL: The RESULT PANEL is a feature only found in Playgrounds and provides immediate feedback.WINDOW PANE CONTROLS: The WINDOW PANE CONTROLS has 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 of these icons 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 in order to make Playgrounds execute code or in order to stop Playgrounds from running. Typically, Playgrounds runs on its own, but sometimes you need to manually toggle it on when Playgrounds does not execute your code for you.

Now that we have our setup finished, delete everything in this file. Your Playground should have three open panels—your Playground editor, Results panel, and Debug panel. Let's start digging into some code.

Comments – leaving yourself notes or reminders

Comments are a great way to create notes or reminders to yourself. When you comment code, it means that it will not be executed when your code runs. There are two types of comments used // or /* */. // is typically used for a one-line comment and /**/ is used for a block of text.

You can add comments to your code, such as a TODO item or just a brief explanation of what something is doing.

Let's see what both of these look like: