iOS 15 Programming for Beginners - Ahmad Sahar - E-Book

iOS 15 Programming for Beginners E-Book

Ahmad Sahar

0,0
43,19 €

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

With almost 2 million apps on the App Store, iOS mobile apps continue to be incredibly popular. Anyone can reach millions of customers around the world by publishing their apps on the App Store. iOS 15 Programming for Beginners is a comprehensive introduction for those who are new to iOS. It covers the entire process of learning the Swift language, writing your own app, and publishing it on the App Store.
Complete with hands-on tutorials, projects, and self-assessment questions, this easy-to-follow guide will help you get well-versed with the Swift language to build your apps and introduce exciting new technologies that you can incorporate into your apps. You'll learn how to publish iOS apps and work with Mac Catalyst, SharePlay, SwiftUI, Swift concurrency, and much more.
By the end of this iOS development book, you'll have the knowledge and skills to write and publish interesting apps, and more importantly, to use the online resources available to enhance your app development journey.

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

EPUB
MOBI

Seitenzahl: 613

Veröffentlichungsjahr: 2021

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.



iOS 15 Programming for Beginners

Sixth Edition

Kickstart your mobile app development journey by building iOS apps with Swift 5.5 and Xcode 13

Ahmad Sahar

Craig Clayton

BIRMINGHAM—MUMBAI

iOS 15 Programming for Beginners

Sixth Edition

Copyright © 2021 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.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Ashitosh Gupta

Senior Editor: Hayden Edwards

Content Development Editor: Aamir Ahmed

Technical Editor: Shubham Sharma

Copy Editor: Safis Editing

Project Coordinator: Kinjal Bari

Proofreader: Safis Editing

Indexer: Manju Arasan

Production Designer: Vijay Kamble

Marketing Coordinator: Elizabeth Varghese

First published: January 2017

Second Edition: January 2018

Third Edition: December 2018

Fourth Edition: January 2020

Fifth Edition: November 2020

Sixth Edition: December 2021

Production reference: 3090622

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80181-124-8

www.packt.com

To my beloved wife, Oni.

– Ahmad Sahar

Contributors

About the authors

Ahmad Sahar is 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 Clayton is a self-taught senior iOS engineer at Fan Reach, specializing in building mobile experiences for NBA, NHL, CHL, 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 is launching a new site called Design To SwiftUI online, which specializes in teaching developers and designers how to build iOS apps from design to SwiftUI video courses.

About the reviewers

Ian Lockett is a skilled freelance mobile application developer based in the UK. With over 20 years' experience in the software industry, he has spent the last 12 years developing iOS and Android apps for a wide range of clients and industries from small startups to large enterprises. His major experience is in iOS development using both Swift and Objective-C and he has also created and maintained Android apps over the last two years using Kotlin. Ian prides himself on his attention to detail and delivering high-quality software. For the last three years, Ian has also been a volunteer co-organizer for the Hacking with Swift Live conference.

Juan Catalan is a software developer with more than 10 years of experience, having started learning iOS almost from the beginning. He has worked as a professional iOS developer in many industries including industrial automation, transportation, document management, fleet tracking, real estate, and financial services. Juan has contributed to more than 30 published apps, some of them with millions of users. He has a passion for software architecture, always looking for ways to write better code and optimize mobile apps.

Anoop Tomar has been in the tech industry for over 15 years with a demonstrated history of working in mobile, artificial intelligence, machine learning, computer visions, and full-stack engineering.

He is a co-founder of DevTechie.com with Neha Vishwakarma. DevTechie.com is an Ed-Tech company that promotes practical learning for anyone and everyone to learn to code and excel in a tech career. His combined published work includes 300+ videos on YouTube, 50+ video courses on Udemy, and 30+ articles on Medium with a focus on iOS, Swift, machine learning, and computer vision. In his free time, he enjoys reading about tech, building apps, traveling, and spending time with his family.

I thank my wife and daughter, who are my whole world. They are the loves of my life and a daily inspiration for me to do great things. I also thank my parents, who have always believed in me and helped me to pursue my passions. Special thanks to all the mentors, teachers, and friends who have stood by my side and supported me.

Table of Contents

Preface

Part 1: Swift

Chapter 1: Getting Familiar with Xcode

Technical requirements

Downloading and installing Xcode from the App Store

Understanding the Xcode user interface

Running the app in the iOS simulator

Understanding the No Devices and Build sections

Using an iOS device for development

Trusting the Developer App certificate on your iOS device

Connecting an iOS device wirelessly

Summary

Chapter 2: Simple Values and Types

Technical requirements

Understanding Swift playgrounds

Customizing fonts and colors

Running playground code

Exploring data types

Representing integers

Representing floating-point numbers

Representing Booleans

Representing 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

Using type safety to check values

Exploring operators

Using arithmetic operators

Using compound assignment operators

Using comparison operators

Using logical operators

Performing string operations

Using the print() statement

Summary

Chapter 3: Conditionals and Optionals

Technical requirements

Introducing conditionals

Using if statements

Using switch statements

Introducing optionals and optional binding

Summary

Chapter 4: Range Operators and Loops

Technical requirements

Exploring Range operators

Exploring Loops

Using the for-in loop

Using the while loop

The repeat-while loop

Summary

Chapter 5: Collection Types

Technical requirements

Understanding arrays

Creating an array

Checking the number of elements in an array

Adding a new element to an array

Accessing an array element

Assigning a new value to a particular index

Removing an element from an array

Iterating over an array

Understanding dictionaries

Creating a dictionary

Checking the number of elements in a dictionary

Adding a new element to a dictionary

Accessing a dictionary element

Assigning a new value to an existing key

Removing an element from a dictionary

Iterating over a dictionary

Understanding sets

Creating a set

Checking the number of elements in a set

Adding a new element to a set

Checking whether a set contains an element

Removing an item from a set

Iterating over a set

Exploring Set operations

Exploring set membership and equality

Summary

Chapter 6: 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

Chapter 7: 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 structure

Comparing value types and reference types

Deciding between classes and structures

Understanding enumerations

Creating an enumeration

Summary

Chapter 8: 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

Part 2: Design

Chapter 9: Setting Up the User Interface

Technical requirements

Learning useful terms in iOS development

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 Photo Filter screen

Using the Map screen

Creating a new Xcode project

Setting up a tab bar controller scene

Setting the titles of the tab bar's buttons

Embedding view controllers in navigation controllers

Adding the Assets.xcassets file

Adding the icons for the Explore and Map buttons

Setting up the Launch screen

Configuring the Launch screen's background color

Adding a logo and constraints to the Launch screen

Configuring Interface Builder

Summary

Chapter 10: Building Your User Interface

Technical requirements

Adding a collection view to the Explore screen

Connecting storyboard elements to outlets in a view controller

Adding a Cocoa Touch Class file to your project

Connecting storyboard elements 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

Configuring storyboard element sizes

Presenting a view modally

Adding a button to the collection view header

Adding a new view controller scene

Adding Cancel and Done buttons to the navigation bar

Summary

Chapter 11: Finishing Up Your User Interface

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

Chapter 12: 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

Part 3: Code

Chapter 13: Getting Started with MVC and Collection Views

Technical requirements

Understanding the Model-View-Controller design pattern

Exploring controllers and classes

Understanding collection views

Revisiting the Explore and Restaurant List screens

Summary

Chapter 14: 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 file

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

Chapter 15: Getting Started with Table Views

Technical requirements

Understanding table views

Creating the LocationViewController class

Connecting the table view to the LocationViewController class

Adding the data source and delegate methods

Adding location data for the table view

Creating the LocationDataManager class

Displaying data in a table view

Summary

Chapter 16: Getting Started with MapKit

Technical requirements

Understanding and creating annotations

Creating the RestaurantItem class

Creating the MapDataManager class

Creating the DataManager protocol

Refactoring the MapDataManager class

Refactoring the ExploreDataManager class

Adding annotations to a map view

Creating the MapViewController class

Connecting the outlets for the map view

Setting the map view region to be displayed

Displaying MKAnnotationView instances on the map view

Creating custom MKAnnotationView instances

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 the ExploreViewController class

Using the // MARK: syntax

Refactoring the RestaurantListViewController class

Refactoring the LocationViewController class

Refactoring the MapViewController class

Summary

Chapter 17: Getting Started with JSON Files

Technical requirements

Getting data from JSON files

Understanding the JSON format

Creating the RestaurantDataManager class

Using data from JSON files in your app

Configuring the MapDataManager instance to use data from the RestaurantDataManager instance

Storing a user-selected location

Adding a UICollectionReusableView subclass for the section header in the Explore screen

Connecting the section header's label to the ExploreViewController class

Adding an unwind action method to the Done button

Selecting only one location in the Locations screen

Passing location and cuisine information to the RestaurantListViewController instance

Creating a view controller for the cells on the Restaurant List screen

Connecting the outlets for the RestaurantCell class

Displaying a custom UIView to indicate no data is available

Displaying a list of restaurants on the Restaurant List screen

Summary

Chapter 18: Displaying Data in a Static Table View

Technical requirements

Setting up outlets for the RestaurantDetailViewController class

Displaying data in the static table view

Passing data to the RestaurantDetailViewController instance

Summary

Chapter 19: Getting Started with Custom UIControls

Technical requirements

Creating a custom UIControl subclass

Displaying stars in your custom UIControl subclass

Adding support for touch events

Implementing an unwind method for the Cancel button

Creating the ReviewFormViewController class

Summary

Chapter 20: Getting Started with Cameras and Photo Libraries

Technical requirements

Understanding filters

Creating model objects for the Photo Filter screen

Creating the ImageFiltering protocol

Creating classes for the Photo Filter screen

Creating a class for the collection view cells

Creating a view controller for the Photo Filter screen

Getting permission to use the camera or photo library

Summary

Chapter 21: 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

Understanding how saving and loading works

Updating the ReviewFormViewController class to save reviews

Passing RestaurantID to the ReviewFormViewController instance

Updating the PhotoFilterViewController class to save photos

Displaying saved reviews and photos on the Restaurant Detail screen

Calculating a restaurant's overall rating

Summary

Part 4: Features

Chapter 22: Getting Started with Mac Catalyst

Technical requirements

Fixing user interface issues

Making your app run on all iOS devices

Identifying device type

Understanding size classes

Updating the Explore screen

Updating the Restaurant List screen

Updating the app to work on macOS

Summary

Chapter 23: Getting Started with SwiftUI

Technical requirements

Creating a SwiftUI Xcode project

Creating the Restaurant List screen

Adding model objects and configuring navigation

Using UIKit and SwiftUI Views together

Completing the Restaurant Detail screen

Summary

Chapter 24: Getting Started with Swift Concurrency

Technical requirements

Understanding Swift Concurrency

Examining an app without concurrency

Updating the app using async/await

Improving efficiency using async-let

Updating RestaurantListViewController to use async/await

Summary

Chapter 25: Getting Started with SharePlay

Technical requirements

Understanding SharePlay

Exploring the ShareOrder app

Creating a custom Group Activity

Adding the Group Activities entitlement

Creating the ShareOrder structure

Activating a custom group activity

Managing a group activity session

Implementing a GroupSession object

Implementing a GroupSessionMessenger object

Testing SharePlay in the ShareOrder app

Summary

Chapter 26: Testing and Submitting Your App to the App Store

Technical requirements

Getting an Apple Developer account

Exploring your Apple Developer account

Generating a certificate signing request

Creating development and distribution certificates

Registering an App ID

Registering your devices

Creating provisioning profiles

Submitting your app to the App Store

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

Part 1: Swift

Welcome to Part 1 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). After that, 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 XcodeChapter 2, Simple Values and TypesChapter 3, Conditionals and Optionals Chapter 4, Range Operators and LoopsChapter 5, Collection TypesChapter 6, Functions and ClosuresChapter 7, Classes, Structures, and EnumerationsChapter 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 part and will also enable you to create your own Swift programs. Let's get started!

Chapter 1: Getting Familiar with Xcode

Welcome to iOS 15 Programming for Beginners. I hope you will find this a useful introduction to creating and publishing iOS 15 apps on the App Store.

In this chapter, you'll learn how to download and install Xcode on your Mac. You'll familiarize yourself with the different parts of the Xcode user interface, and you'll create your first iOS app and run it in the iOS simulator. You will then learn 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 will learn 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.

By the end of this chapter, you will know how to create and run apps on the iOS simulator or an iOS device, which you will need to do when you build your own apps.

The following topics will be covered:

Downloading and installing Xcode from the App StoreUnderstanding the Xcode user interfaceRunning the app in the iOS simulatorUsing an iOS device for development

Technical requirements

To do the exercises for this chapter, you will need the following:

An Apple Mac computer running macOS 11 Big Sur or macOS 12 MontereyAn Apple ID (if you don't have one, you will create one in this chapter) Optionally, an iOS device running iOS 15

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-15-Programming-for-Beginners-Sixth-Edition

Check out the following video to see the code in action:

https://bit.ly/3wqcqpG

You'll start by downloading Xcode, Apple's integrated development environment (IDE) for developing iOS apps from the App Store, in the next section.

Tip

The size of the download is very large (11.7 GB at the time of writing) so it may take a while to download. Ensure that you have enough disk space prior to downloading.

Downloading and installing Xcode from the App Store

Before you begin writing iOS apps, you need to download and install Xcode from the App Store. To do this, follow these steps:

Choose App Store from 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. Click 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:

Figure 1.1: Apple ID creation dialog box

Important Information

You can see more information on how to create an Apple ID using this link: https://support.apple.com/en-us/HT204316#appstore.

Once Xcode has been installed, launch it. You should see the following Welcome to Xcode screen. Click Create a new Xcode project in the left-hand pane:

Figure 1.2: Welcome to Xcode screen

You will see the new project screen as follows. In the Choose a template for your new project: section, select iOS. Then choose App and click Next:

Figure 1.3: Choose a template for your new project screen

You will see the Choose options for your new project: screen:

Figure 1.4: Choose options for your new project screen

Configure this options screen as follows:

Product Name: The name of your app. Enter ExploringXcode in the text field.Organization Identifier: Used to create a unique identifier for your app on the App Store. Enter com.yourname for now. This is known as reverse domain name notation format, and is normally used here.Interface: The method used to create the user interface for your app. Set this to Storyboard.Language: The programming language to be used. Set this to Swift.

Leave the other settings as their default values and make sure all the checkboxes are unticked. Click Next when done.

You'll see a Save dialog box. Choose a location to save your project, such as the Desktop or Documents folder, and click Create:

Figure 1.5: Save dialog box

If you see a dialog box saying No author information was supplied by the version control system, click Fix.

Important Information

The reason why you see this dialog box is because the Source Control checkbox is ticked. Apple recommends that Source Control be turned on. Source Control is outside the scope of this book but if you wish to learn more about version control and Git, see this link: https://git-scm.com/video/what-is-version-control.

You will see the Source Control preference screen as follows:

Figure 1.6: Source Control preference screen

Enter the following information:

Author Name: – Your own nameAuthor Email: – Your email address

Close the Source Control preference screen by clicking the red Close button in the top-left corner when done. The Xcode main window will appear.

Fantastic! You have now successfully downloaded and installed Xcode and created your first project. In the next section, you will learn about the Xcode user interface.

Understanding the Xcode user interface

You've just created your first Xcode project! As you can see, the Xcode user interface is divided into several distinct parts, as shown here:

Figure 1.7: Xcode user interface

Let's look at each part in more detail. The following descriptions correspond to the numbers shown in the preceding screenshot:

Toolbar (1) – Used to build and run your apps, and view the progress of running tasks.Navigator area (2) – Provides quick access to the various parts of your project. The Project navigator is displayed by default. Editor area (3) – Allows you to edit source code, user interfaces, and other resources. Inspector area (4) – Allows you to view and edit information about items selected in the Navigator area or Editor area. Debug area (5) – Contains the debug bar, the variables view, and the Console. The Debug area is toggled by typing Shift + Command + Y.

Next, let's examine the toolbar more closely. The left side of the toolbar is shown here:

Figure 1.8: Xcode toolbar (left side)

Let's look at each part in more detail. The following description corresponds to the numbers shown in the preceding screenshot:

Navigator button (1) – Toggles the Navigator area on and off.Stop button (2) – Only appears next to the Play button when the app is running. Stops the currently running app.Play button (3) – Used to build and run your app.Scheme menu (4) – Shows the specific scheme to build your project (Exploring Xcode) and the destination to run your app on (iPhone SE (2nd generation).

Schemes and destinations are distinct. Schemes specify the settings for building and running your project. Destinations specify installation locations for your app, and exist for physical devices and simulators.

Activity View (5) - Displays the progress of running tasks.

The right side of the toolbar is shown here:

Figure 1.9: Xcode toolbar (right side)

Let's look at each part in more detail. The following description corresponds to the numbers shown in the preceding screenshot:

Library button (1) – Displays user interface elements, code snippets, and other resources.Inspector button (2) – Toggles the Inspector area on and off.

Don't be overwhelmed by all the different parts, as you'll learn about them in more detail in later chapters. Now that you are familiar with the Xcode interface, you will run the app you just created in the iOS simulator, which displays a representation of your iOS device.

Running the app in the iOS simulator

The iOS simulator is installed when you install Xcode. It provides a simulated iOS device so that you can see what your app looks like and how it behaves, without needing a physical iOS device. It can model all the screen sizes and resolutions for both iPad and iPhone so you can test your app on multiple devices easily.

To run your app in the simulator, follow these steps:

Click the Scheme menu in the toolbar and you will see a list of simulators. Choose iPhone SE (2nd generation) from this menu:

Figure 1.10: Xcode Scheme menu with iPhone SE (2nd generation) selected

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 username and password of the Mac's administrator account, and click Continue.The simulator will launch and show a representation of an iPhone SE (2nd generation). Your app displays a white screen, as you have not yet added anything to your project:

Figure 1.11: iOS Simulator

Switch back to Xcode and click on the Stop button (or press 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 wonder what the No Devices and Build sections are for. Let's a look at them in the next section.

Important Information

If you are using an M1 Mac you will see My Mac (Designed for iPad) instead of No Devices in the Scheme menu.

Understanding the No Devices and Build sections

You learned how to choose a simulator in the Scheme menu to run your app in the previous section. In addition to the list of simulators, the Scheme menu also has No Devices and Build sections. These allow you to run apps on actual iOS devices, and prepare apps for submission to the App Store.

Click the Scheme menu in the toolbar to see the No Devices and Build sections at the top of the menu:

Figure 1.12: Xcode Scheme menu with Any iOS Device (arm64) selected

The No Devices 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 section has only one menu item, Any iOS Device (arm64). 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 Chapter 26, Testing and Submitting Your App to the App Store.

Now let's see how to build and run your app on an actual iOS 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.

Using an iOS device for development

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.

Important Information

For a comprehensive look at all the differences between the Simulator and an actual device, see this link: https://help.apple.com/simulator/mac/current/#/devb0244142d.

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 to download Xcode from the App Store for now. Follow these steps:

Use the cable that came with your iOS device to connect your device to your Mac, and make sure the iOS device is unlocked.

Tip

You can view connected devices by choosing Window | Devices and Simulators in the Xcode menu bar.

In the Scheme menu, choose your device (iPhone in this case) as the run destination:

Figure 1.13: Xcode Scheme menu with actual iOS device selected

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 clicking the Play button (or use Command + R). You will get the following error: Signing for "Exploring Xcode" requires a development team.:

Figure 1.14: Xcode Signing & Capabilities pane

This is because a digital certificate is required to run the app on an iOS device, and you need to add an Apple ID or paid Apple Developer account to Xcode so the digital certificate can be generated.

Important Information

Using an Apple ID will allow you to test your app on an iOS device, but you will need a paid Apple Developer account to distribute apps on the App Store. You'll learn more about this in Chapter 26, Testing and Submitting Your App to the App Store.

Important Information

Certificates ensure that the only apps that run on your device are the ones you authorize. This helps to protect against malware. You can also learn more about them at this link: https://help.apple.com/xcode/mac/current/#/dev60b6fbbc7.

Click the Add Account... button:

Figure 1.15: Xcode Signing & Capabilities pane with Add Account... button selected

The Xcode Preferences window appears with the Accounts pane selected. Enter your Apple ID and click Next:

Figure 1.16: Apple ID sign in dialog box

Tip

You can also access Xcode preferences by choosing Preferences in the Xcode menu.

Enter your password when prompted. After a few minutes, the Accounts pane will display your account settings:

Figure 1.17: Accounts pane in Xcode preferences

Close the Preferences window when you're done by clicking the red Close button in the top-left corner.In Xcode's Editor area, click Signing & Capabilities. Make sure Automatically manage signing is ticked and Personal Team is selected from the Team pop-up menu:

Figure 1.18: Xcode Signing & Capabilities pane with account set

If you still see errors in this screen, try changing your Bundle Identifier by typing some random characters into it, for example, com.myname4352.ExploringXcode.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:

Figure 1.19: Could not launch "ExploringXcode" dialog box

This means you need to trust the certificate that has been installed on your device. You'll learn how to do this in the next section.

Trusting the Developer App certificate on your iOS device

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. Follow these steps:

On your iOS device, tap Settings | General | VPN & Device Management:

Figure 1.20: Device Management setting in iOS Settings

Tap Apple Development:

Figure 1.21: Apple Development section in Device Management settings

TapTrust "Apple Development: ":

Figure 1.22: Trust button

Tap Trust:

Figure 1.23: Trust dialog box

You should see the following text, which shows the app is now trusted:

Figure 1.24: Apple Development section with trusted certificate

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 device to your Mac using the cable to build and run your app. You'll learn how to connect to your device over Wi-Fi in the next section.

Connecting an iOS device wirelessly

Unplugging and replugging your iOS device to your Mac gets pretty cumbersome after a while, so you'll configure Xcode to connect to your iOS device over Wi-Fi now. Follow these steps:

Make sure your iOS device is plugged into your Mac, and both the Mac and iOS device are on the same wireless network.Choose Window | Devices and Simulators from the Xcode menu bar:

Figure 1.25: Xcode Window menu with Devices and Simulators selected

Click on the checkbox marked Connect via network:

Figure 1.26: Xcode Devices and Simulators Window with Connect via network checked

Awesome! Your iOS device is now connected wirelessly to Xcode, and you no longer need the USB cable to be connected to it.

Summary

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 No Device and Generic iOS Device menu items are for. This enables you to create and run iOS apps on your Mac without requiring an iOS device.

You learned how to connect an iOS device to Xcode via USB so that you can run the app on it. You added an Apple ID to Xcode so the necessary digital certificates can be created and installed on your device, and trusted the certificate on your device. This gives you the ability to run your apps on an actual device, so you can more accurately determine their performance, and make use of features not available in the iOS simulator.

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. This makes it much more convenient to build and test your apps on an iOS device as any new builds can be transferred immediately over the air.

In the next chapter, you'll start exploring the Swift language using Swift Playgrounds, and learn how simple values and types are implemented in Swift.

Invitation to join us on Discord

Read this book alongside other iOS developers and the author Ahmad Sahar.

Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions and much more.

Scan the QR code or visit the link to join the community.

https://packt.link/iosdevelopment