29,99 €
In a world with nearly 2 million apps on the App Store, the demand for skilled iOS developers has never been higher. "iOS 17 Programming for Beginners, Eighth Edition" is your gateway to this lucrative and dynamic field. This hands-on guide is tailored for those who are new to iOS and takes you on a journey from learning the Swift language to crafting your own app and seeing it thrive on the App Store.
Our approach is hands-on and practical. Each chapter is designed to be a stepping stone in your development journey, providing step-by-step tutorials, real-life examples, and clear explanations of complex concepts. As you progress, you'll not only be skilled in Swift but also incorporate cutting-edge technologies into your apps. You'll learn how to publish your creations and harness the power of iOS 17 through a straightforward and easy to program example app divided into manageable parts.
By the time you've completed this book, you'll possess the skills and knowledge to not only develop and publish captivating apps but also leverage online resources to continually enhance your app development prowess.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 512
Veröffentlichungsjahr: 2023
iOS 17 Programming for Beginners
Eighth Edition
Unlock the world of iOS development with Swift 5.9, Xcode 15, and iOS 17 – your path to App Store success
Ahmad Sahar
BIRMINGHAM—MUMBAI
iOS 17 Programming for Beginners
Eighth Edition
Copyright © 2023 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.
Senior Publishing Product Manager: Larissa Pinto
Acquisition Editor – Peer Reviews: Gaurav Gavas
Project Editor: Meenakshi Vijay
Content Development Editor: Matthew Davies
Copy Editor: Safis Editing
Technical Editor: Aniket Shetty
Proofreader: Safis Editing
Indexer: Hemangini Bari
Presentation Designer: Rajesh Shirsath
Developer Relations Marketing Executive: Sohini Ghosh
First published: October 2016
Second edition: January 2018
Third edition: November 2018
Fourth edition: January 2020
Fifth edition: November 2020
Sixth edition: November 2021
Seventh edition: November 2022
Eighth edition: October 2023
Production reference: 1261023
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-83763-056-1
www.packt.com
Ahmad Sahar is a trainer, presenter, and consultant at Tomafuwi Productions. He specializes in conducting training courses for iOS development, including the macOS Support Essentials certification. 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.
To my mother, Sharifah; my father, Sahar; my two sisters, Ainol Shareha and Ainol Shaharina; and my beloved wife, Oni – thank you for your love and support.
Artem Novichkov is an iOS developer whose passion lies in the Swift programming language and open source. While his primary focus is his work for Welltory, he actively engages in various educational projects and serves as a mentor across different platforms, where he guides aspiring developers through their unique challenges. In his spare time, he likes playing video games and soaring through the skies with his drones.
Many thanks to my wife and my mother for their patience and endless support.
Tim Oliver is an iOS software engineer currently working for Instagram in Tokyo, Japan. Originally from Perth in Australia, Tim started his career as a web developer before moving to iOS software engineering full-time in 2013, working at a variety of companies, including startups like Realm and Drivemode.
Tim is also active in the iOS developer community, presenting at and helping to facilitate many Apple developer conferences around the world. He also regularly runs a local iOS meetup named Tokyo iOS.
Outside of work, Tim is a huge fan of open source software, publishing a variety of libraries and UI components on his GitHub page, and contributing to some of the larger open source projects, including IGListKit and YT Music.
Many thanks to my parents, Ronald and Helen Oliver, the two biggest champions in my life, and whose love and support got me this far. Also, a huge shoutout to all my friends and colleagues in Japan and Australia, most notably Will Bailey, Jetha Chan, Darren Lewis, Dean Herbert, and Jon Hayward for their excellent technical advice and support throughout this endeavor.
To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:
https://packt.link/8hBmp
Preface
Who this book is for
What this book covers
To get the most out of this book
Get in touch
Part 1: Swift
Exploring Xcode
Technical requirements
Downloading and installing Xcode from the App Store
Exploring the Xcode user interface
Running your app in Simulator
Understanding the Devices and Build sections
Running your app on an iOS device
Trusting the Developer App certificate on your iOS device
Summary
Simple Values and Types
Technical requirements
Introducing Swift playgrounds
Customizing fonts and colors
Running playground code
Exploring data types
Representing integers
Representing floating-point numbers
Representing strings
Representing Booleans
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
Conditionals and Optionals
Technical requirements
Introducing conditionals
Using if statements
Using switch statements
Introducing optionals and optional binding
Summary
Range Operators and Loops
Technical requirements
Exploring range operators
Exploring loops
The for-in loop
The while loop
The repeat-while loop
Summary
Collection Types
Technical requirements
Exploring 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 specified index
Removing an element from an array
Iterating over an array
Exploring 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
Exploring 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
Performing set operations
Understanding set membership and equality
Summary
Functions and Closures
Technical requirements
Exploring 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
Exploring closures
Simplifying closures
Summary
Classes, Structures, and Enumerations
Technical requirements
Understanding classes
Creating a class declaration
Making an instance of the class
Making a subclass
Overriding a superclass method
Understanding structures
Creating a structure declaration
Making an instance of the structure
Comparing value types and reference types
Deciding between classes and structures
Understanding enumerations
Creating an enumeration
Summary
Protocols, Extensions, and Error Handling
Technical requirements
Exploring protocols
Creating a protocol declaration
Exploring extensions
Adopting a protocol via an extension
Creating an array of different types of objects
Exploring error handling
Summary
Swift Concurrency
Technical requirements
Understanding Swift concurrency
Examining an app without concurrency
Updating the app using async/await
Improving efficiency using async-let
Summary
Part 2: Design
Setting Up the User Interface
Technical requirements
Learning useful terms in iOS development
A tour of the JRNL app
Using the Journal List screen
Using the Add New Journal Entry screen
Using the Journal Entry Detail screen
Using the Map screen
Modifying your Xcode project
Setting up a tab bar controller scene
Setting the tab bar button titles and icons
Embedding view controllers in navigation controllers
Configuring Interface Builder
Summary
Building Your User Interface
Technical requirements
Adding a table view to the Journal List screen
Connecting storyboard elements to the view controller
Configuring data source methods for the table view
Setting the delegate and data source properties of the table view
Adopting the UITableViewDataSource and UITableViewDelegate protocols
Presenting a view modally
Adding a bar button to the navigation bar
Adding a new view controller scene
Adding Cancel and Save buttons to the navigation bar
Summary
Finishing Up Your User Interface
Technical requirements
Implementing the Journal Entry Detail screen
Implementing the Map screen
Summary
Modifying App Screens
Technical requirements
Modifying the Journal List screen
Adding an image view to journalCell
Adding labels to journalCell
Modifying the Add New Journal Entry screen
Adding a custom view to the New Entry scene
Adding a switch to the New Entry scene
Adding a text field and a text view to the New Entry scene
Adding an image view to the New Entry scene
Embedding user interface elements in a stack view
Modifying the Journal Entry Detail screen
Configuring the number and size of static table view cells
Adding user interface elements to static table view cells
Summary
Part 3: Code
Getting Started with MVC and Table Views
Technical requirements
Understanding the Model-View-Controller design pattern
Exploring view controllers
Understanding table views
Conforming to the UITableViewDataSource protocol
Conforming to the UITableViewDelegate protocol
Creating a TableViewExampleController instance
Revisiting the Journal List screen
Summary
Getting Data into Table Views
Technical requirements
Understanding model objects
Creating a class to represent a journal entry
Creating sample data
Displaying data in a table view
Creating a custom UITableViewCell subclass
Connecting the outlets in journalCell
Updating the data source methods in JournalListViewController
Summary
Passing Data between View Controllers
Technical requirements
Passing data from the Add New Journal Entry screen to the Journal List screen
Creating the AddJournalEntryViewController class
Connecting the UI elements to the AddJournalEntryViewController class
Creating a JournalEntry instance from user input
Updating the table view with a new journal entry
Removing rows from a table view
Exploring text field and text view delegate methods
Passing data from the Journal List screen to the Journal Entry Detail screen
Creating the JournalEntryDetailViewController class
Connecting the UI elements to the JournalEntryDetailViewController class
Displaying the details of a journal entry
Displaying the details of a selected journal entry
Summary
Getting Started with Core Location and MapKit
Technical requirements
Getting your device location using the Core Location framework
Modifying the AddJournalEntryViewController class
Modifying the Info.plist file
Creating the MapViewController class
Updating the JournalEntry class to conform to the MKAnnotation protocol
Displaying annotation views on the Map screen
Configuring a pin to display a callout
Going from the Map screen to the Journal Entry Detail screen
Displaying a map snapshot on the Journal Entry Detail screen
Summary
Getting Started with JSON Files
Technical requirements
Creating a singleton
Modifying the JournalEntry class to be JSON-compatible
Loading and saving JSON data
Summary
Getting Started with Custom Views
Technical requirements
Creating a custom UIStackView subclass
Adding your custom view to the Add New Journal Entry screen
Adding your custom view to the Journal Entry Detail screen
Summary
Getting Started with the Camera and Photo Library
Technical requirements
Creating a new UIImagePickerController instance
Implementing UIImagePickerControllerDelegate methods
Getting permission to use the camera or photo library
Summary
Getting Started with Search
Technical requirements
Implementing a search bar for the Journal List screen
Modifying table view data source methods
Modifying the prepare(for:sender:) method
Modifying the method to remove journal entries
Summary
Getting Started with Collection Views
Technical requirements
Understanding collection views
Modifying the Journal List screen to use a collection view
Replacing the table view with a collection view
Adding user interface elements to the collection view cell
Modifying the JournalListTableViewCell class
Modifying the JournalListViewController class
Dynamically modifying collection view cell size using size classes
Understanding size classes
Modifying the JournalListViewController class
Testing your app on different devices
Summary
Part 4: Features
Getting Started with SwiftData
Technical requirements
Introducing SwiftData
Modifying the JournalEntry class
Implementing SwiftData components
Modifying the JournalListViewController class
Summary
Getting Started with SwiftUI
Technical requirements
Creating a SwiftUI Xcode project
Creating the Journal List screen
Adding model objects and configuring navigation
Using MapKit for SwiftUI
Completing the Journal Entry Detail screen
Summary
Getting Started with Widgets
Technical requirements
Introducing widgets
Adding a widget target to your app
Providing timeline entries to your widget
Customizing your widget’s view
Adding a widget to your Home and Lock screens
Summary
Getting Started with visionOS
Technical requirements
Introducing visionOS
Adding a visionOS target to your project
Improving your app’s appearance in visionOS
Adding 3D objects to your app
Summary
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
Index
Cover
Index
Welcome to iOS 17 Programming for Beginners. This book is the eighth edition of the iOS Programming for Beginners series, and has been fully updated for iOS 17, macOS 14.0 Sonoma, and Xcode 15.
In this book, you will build a journal app called JRNL. You will start off by exploring Xcode, Apple’s programming environment, also known as its Integrated Development Environment (IDE). Next, you will start learning the foundations of Swift, the programming language used in iOS apps, and see how it is used to accomplish common programming tasks.
Once you have a solid foundation of using Swift, you will start creating the user interface of the JRNL app. During this process, you will work with storyboards and connect your app’s scenes together using segues.
With your user interface complete, you will then add code to implement your app’s functionality. To start, you’ll learn how to display data using a table view. Next, you’ll learn how to add data to your app, and how to pass data between view controllers. After that, you’ll learn how to determine your device location, and display annotations on a map. You’ll then learn how to persist app data using JSON files, create custom views, and add photos from the camera or photo library. Finally, you’ll make your app work on devices with larger screens, such as iPad or Mac, by implementing a collection view in place of a table view.
You now have a complete app, but how about adding the latest iOS 17 features? You’ll start by learning about SwiftData, which allows you to describe data models and manipulate model instances using regular Swift code. Next, you will learn how to develop apps using SwiftUI, a great new way of developing apps for all Apple platforms. After that, you’ll implement widgets using WidgetKit, and learn the basics of how to get your app running on Apple’s latest platform for spatial computing, visionOS.
Finally, you’ll learn how to test your app with internal and external testers, and get it into the App Store.
This book is tailored for individuals with minimal coding experience who are new to the world of Swift and iOS app development. A basic understanding of programming concepts is recommended.
Chapter 1, Exploring Xcode, takes you through a tour of Xcode and talks about all the different parts that you will use throughout the book.
Chapter 2, Simple Values and Types, deals with how values and types are implemented by the Swift language.
Chapter 3, Conditionals and Optionals, shows how if and switch statements are implemented, and how to implement variables that may or may not have a value.
Chapter 4, Range Operators and Loops, shows how to work with ranges and the different ways loops are implemented in Swift.
Chapter 5, Collection Types, covers the common collection types, which are arrays, dictionaries, and sets.
Chapter 6, Functions and Closures, covers how you can group instructions together using functions and closures.
Chapter 7, Classes, Structures, and Enumerations, talks about how complex objects containing state and behavior are represented in Swift.
Chapter 8, Protocols, Extensions, and Error Handling, talks about creating protocols complex data types can adopt, extending the capabilities of existing types, and how to handle errors in your code.
Chapter 9, Swift Concurrency, introduces you to the concepts of parallel and asynchronous programming, and shows you how you can implement it in your app.
Chapter 10, Setting Up the User Interface, deals with creating the JRNL app and setting up the initial screen the users will see.
Chapter 11, Building Your User Interface, covers setting up the main screen for the JRNL app.
Chapter 12, Finishing Up Your User Interface, covers setting up the remaining screens for the JRNL app.
Chapter 13, Modifying App Screens, is about configuring each screen of the app in a storyboard.
Chapter 14, Getting Started with MVC and Table Views, concerns working with a table view and how you can use it to display a list of items.
Chapter 15, Getting Data into Table Views, concerns the incorporation of data into table views using an array as a data source.
Chapter 16, Passing Data between View Controllers, teaches you how to add data entered using a view controller to an array, and how to pass data from the array to another view controller.
Chapter 17, Getting Started with Core Location and MapKit, deals with working with Core Location and MapKit to determine your device location and to add annotations on a map.
Chapter 18, Getting Started with JSON Files, involves learning how to store and retrieve user data using a JSON file.
Chapter 19, Getting Started with Custom Views, teaches you how to create and use a custom view that displays a star rating.
Chapter 20, Getting Started with the Camera and Photo Library, talks about how to get photos from your camera or photo library into your app.
Chapter 21, Getting Started with Search, teaches you how to implement a search bar for your main screen.
Chapter 22, Getting Started with Collection Views, shows you how to implement collection views in place of table views to suit devices with larger screens, such as Mac or iPad.
Chapter 23, Getting Started with SwiftData, deals with implementing Apple’s new SwiftData framework to persist data on your app.
Chapter 24, Getting Started with SwiftUI, introduces building an app using Apple’s new SwiftUI technology.
Chapter 25, Getting Started with Widgets, teaches you how to create widgets for iPhone, iPad and Mac using WidgetKit.
Chapter 26, Getting Started with visionOS, shows you how to prepare your app for Apple’s latest platform, visionOS.
Chapter 27, Testing and Submitting Your App to the App Store, concerns how to test and submit your apps to the App Store.
This book has been completely revised for iOS 17, macOS 14.0 Sonoma, Xcode 15, and Swift 5.9. Part 4 of this book also covers the latest technologies introduced by Apple during WWDC 2023, which are SwiftData, SwiftUI, widgets, and visionOS.
To complete all the exercises in this book, you will need:
A Mac computer running macOS 13.0 Ventura, macOS 14.0 Sonoma, or laterXcode 15.0 or laterTo check if your Mac supports macOS 14.0 Sonoma, see this link: https://www.apple.com/my/macos/sonoma/. If your Mac is supported, you can update macOS using Software Update in System Preferences.
To get the latest version of Xcode, you can download it from the Apple App Store. Most of the exercises can be completed without an Apple Developer account and use the iOS Simulator. If you wish to test the app you are developing on an actual iOS device, you will need a free or paid Apple Developer account, and the following chapters require a paid Apple Developer account:
Chapter 27, Testing and Submitting Your App to the App StoreInstructions on how to get a paid Apple Developer account are in Chapter 27, Testing and Submitting Your App to the App Store.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/iOS-17-Programming-for-Beginners-Eighth-Edition. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Visit the following link to check out videos of the code being run:
https://www.youtube.com/playlist?list=PLeLcvrwLe18524WgmKUez42tO6ppl2O76
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/gbp/9781837630561
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “So, this is a very simple function, named serviceCharge().”
A block of code is set as follows:
classClassName { property1 property2 property3 method1() { code } method2() { code } }When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
let cat Animal() cat.name "Cat"cat.sound "Mew"cat.numberOfLegs 4print(cat.name)Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: “Launch Xcode and click Create a new Xcode project:”
Important notes
appear like this.
Tips
appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Once you’ve read iOS 17 Programming for Beginners, Eighth Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781837630561
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyWelcome 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, Exploring XcodeChapter 2, Simple Values and TypesChapter 3, Conditionals and OptionalsChapter 4, Range Operators and LoopsChapter 5, Collection TypesChapter 6, Functions and ClosuresChapter 7, Classes, Structures, and EnumerationsChapter 8, Protocols, Extensions, and Error HandlingChapter 9, Swift ConcurrencyBy the end of this part, you’ll understand the process of creating an app and running it on Simulator or a device, and you’ll have a working knowledge of how to use the Swift programming language, in order to accomplish common programming tasks. This will prepare you for the next chapter and will also enable you to create your own Swift programs. Let’s get started!
Welcome to iOS 17 Programming for Beginners. I hope you will find this a useful introduction to creating and publishing iOS 17 apps on the App Store.
In this chapter, you’ll download and install Xcode on your Mac. Then, you’ll explore the Xcode user interface. After that, you’ll create your first iOS app and run it in Simulator. Finally, you’ll run your app on an iOS device.
By the end of this chapter, you will know how to create an iOS app, how to run it in Simulator, and how to run in on an iOS device.
The following topics will be covered in this chapter:
Downloading and installing Xcode from the App StoreExploring the Xcode user interfaceRunning your app in SimulatorRunning your app on an iOS deviceTo do the exercises for this chapter, you will need the following:
An Apple Mac computer (Apple Silicon or Intel) running macOS 13 Ventura or macOS 14 SonomaAn Apple ID (if you don’t have one, you will create one in this chapter)Optionally, an iOS device running iOS 17The 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-17-Programming-for-Beginners-Eighth-Edition
Check out the following video to see the code in action:
https://youtu.be/T-0fMJj2vq8
You’ll start by downloading Xcode, Apple’s integrated development environment (IDE) for developing iOS apps from the App Store, in the next section.
The size of the download is very large (10.10 GB at the time of writing) so it may take a while to download. Ensure that you have enough disk space prior to downloading.
Xcode is Apple’s IDE for developing macOS, iOS, iPadOS, watchOS, tvOS, and visionOS apps. You’ll need to download and install Xcode prior to writing your first app. 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’ll see Xcode in the search results. Click Get and then click Install.If you have an Apple ID, type it in the Apple ID text box and enter your password when prompted. 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
You can see more information on how to create an Apple ID using this link: https://support.apple.com/en-us/HT204316#appstore.
Figure 1.2: License agreement screen
You’ll be prompted to enter your Mac’s administrator username and password. Once you have done so, click OK:Figure 1.3: Prompt for administrator username and password
You’ll see a screen showing you the available development platforms. You just need macOS and iOS for now. Leave the settings at their default values and click on Download and Install:Figure 1.4: Development platforms screen
If you are using an Apple Silicon Mac and have not yet installed Rosetta, which allows Intel-based Mac apps to run on Apple Silicon Macs, you’ll be prompted to install it now. Click on Install:Figure 1.5: Rosetta prompt
You’ll see a What’s New in Xcode screen. Click on Continue:Figure 1.6: What’s New in Xcode screen
You’ll see the Welcome to Xcode screen. Click on Create New Project... in the left-hand pane:Figure 1.7: Welcome to Xcode screen
Xcode will start to download iOS 17.0 Simulator automatically. Note that you will not be able to run any apps on Simulator until this process has been completed:Figure 1.8: Simulator download progress bar
You’ll 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.9: Choose a template for your new project: screenYou’ll see the Choose options for your new project: screen:Figure 1.10: Choose options for your new project: screen
Configure the options as follows:
Product Name: The name of your app. Enter JRNL in the text field.Organization Identifier: Used to create a unique identifier for your app on the App Store. Enter com.myname for now. This is known as reverse domain name notation format and is commonly used by iOS developers.Interface: The method used to create the user interface for your app. Set this to Storyboard.Include Tests: Uncheck this check box.Leave the other settings at their default values. Click on 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 on Create:Figure 1.11: Save dialog box
You’ll see a dialog box saying Git Repository Creation Failed. Click on Fix.The reason why you see this dialog box is because the Source Control checkbox in the Save dialog box was 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.
Figure 1.12: Source Control preference screen
Enter the following information:
Author Name: Your own nameAuthor Email: Your email addressClose the Source Control screen by clicking the 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.
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.13: Xcode user interface
Let’s look at each part in more detail. The following description corresponds 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 pressing Shift + Command + Y.Next, let’s examine the toolbar more closely. The left side of the toolbar is shown here:
Figure 1.14: Xcode toolbar (left side)
Let’s look at each part in more detail. The following descriptions correspond to the numbers shown in the preceding screenshot:
Navigator button (1) – Used to display and hide the Navigator area.Stop button (2) – Only appears next to the Run button when the app is running. Stops the currently running app.Run button (3) – Used to build and run your app.Scheme menu (4) – Shows the specific scheme to build your project (JRNL) and the destination to run your app on (iPhone SE (3rd 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 Simulator and physical devices.
Activity view (5) – Displays the progress of running tasks.The right side of the toolbar is shown here:
Figure 1.15: Xcode toolbar (right side)
Let’s look at each part in more detail. The following descriptions correspond to the numbers shown in the preceding screenshot:
Xcode Cloud button (1) – Allows you to sign in to Xcode Cloud, a continuous integration and delivery service built into XcodeLibrary button (2) – Displays user interface elements, code snippets, and other resourcesInspector button (3) – Used to display and hide the Inspector areaDon’t be overwhelmed by all the different parts, as you’ll learn about them in more detail in the upcoming chapters. Now that you are familiar with the Xcode interface, you will run the app you just created in Simulator, which displays a representation of an iOS device.
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 Simulator, follow these steps:
Click the Destination pop-up menu to view a list of simulated devices. Choose iPhone SE (3rd generation) from this menu:Figure 1.16: Xcode Destination pop-up menu with iPhone SE (3rd generation) selected
Click the Run button to install and run your app on the currently selected simulator. You can also use the Command + R keyboard shortcut.Simulator will launch and show a representation of an iPhone SE (3rd generation). Your app displays a white screen, as you have not yet added anything to your project:Figure 1.17: 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 Simulator! Great job!
Now, you may be wondering what the Devices and Build sections in the Destination menu are used for. Let’s look at them in the next section.
You learned how to choose a simulated device in the Destination menu to run your app in the previous section. In addition to the list of simulated devices, this menu also has 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 Destination menu in the toolbar to see the Devices and Build sections at the top of the menu:
Figure 1.18: Xcode Destination menu showing Devices and Build sections
If you have an Apple Silicon Mac, the Devices section will display text stating My Mac (Designed for iPad), because Apple Silicon Macs can run iOS apps. Otherwise, No Devices will be displayed. 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 Simulator will not accurately reflect the performance characteristics of an actual iOS device and does not have hardware features that actual devices have.
The Build section has two menu items, Any iOS Device(arm64) and Any iOS Simulator Device (arm64, x86_64). These are 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 27, 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. Most of the instructions in this book do not require you to have an iOS device though, so if you don’t have one, you can skip the next section and go straight to Chapter 2, Simple Values and Types.
Although you’ll be able to go through most of the exercises in this book using Simulator, it is recommended to build and test your apps on an actual iOS device, as Simulator will not be able to simulate some hardware components and software APIs.
For a comprehensive look at all the differences between 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 (used to automatically create a free Apple developer account) or a paid Apple developer account to build and run your app on your device. You can use the same Apple ID that you used to download Xcode from the App Store. To run your app on an iOS device, 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.Your iOS device will display a Trust This Computer alert. Tap Trust and key in your device passcode when prompted.Your Mac will display an Allow Accessory to Connect alert. Click Allow. Your iOS device is now connected to your Mac and will appear in Xcode’s Destination menu.You can view connected devices by choosing Window | Devices and Simulators in the Xcode menu bar.
Figure 1.19: Xcode Destination menu showing iPhone with Developer Mode disabled
Developer Mode was introduced by Apple during their World Wide Developer Conference in 2022 (WWDC 2022), and is required to install, run, and debug your apps on devices running iOS 16 or greater.
To watch a WWDC 2022 video on Developer Mode, click this link: https://developer.apple.com/videos/play/wwdc2022/110344/.
Figure 1.20: Alert showing Developer Mode is not turned on
To enable Developer Mode on your iOS device, go to Settings | Privacy & Security, scroll down to the Developer Mode item, and tap it.Turn the Developer Mode switch on:Figure 1.21: Developer Mode switch
An alert will appear to warn you that Developer Mode reduces the security of your iOS device. Tap the alert’s Restart button.After your iOS device restarts and you unlock it, confirm that you want to enable Developer Mode by tapping Turn On and entering your iOS device’s passcode.Verify that the (Developer Mode disabled) text no longer appears next to your iOS device in the Destination menu:Figure 1.22: Xcode Destination menu with an 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. Your iOS device is now ready to install and run apps from Xcode.Run the project by clicking the Run button (or use Command + R). You will get the following error in Xcode’s Signing & Capabilities pane, Signing for “JRNL” requires a development team:Figure 1.23: Xcode Signing & Capabilities panel
This is because a digital certificate is required to run the app on an iOS device, and you need to add a free or paid Apple Developer account to Xcode so the digital certificate can be generated.
Using an Apple ID to create a free developer account will allow you to test your app on an iOS device, but it will only be valid for 7 days. Also, you will need a paid Apple Developer account to distribute apps on the App Store. You’ll learn more about this in Chapter 27, Testing and Submitting Your App to the App Store.
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.
Figure 1.24: Xcode Signing & Capabilities pane with Add Account… button selected
The Xcode Settings window appears with the Accounts pane selected. Enter your Apple ID and click Next:Figure 1.25: Apple ID creation dialog box
Note that you can create a different Apple ID if you wish using the Create Apple ID button.
You can also access the Xcode settings by choosing Settings in the Xcode menu.
Figure 1.26: Accounts pane in Xcode preferences
Close the Settings 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.27: Xcode Signing & Capabilities pane with account set
If you still see errors on this screen, try changing your Bundle Identifier by typing some random characters into it, for example, com.myname4352.JRNL.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.28: Could not launch “JRNL” 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.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.29: VPN & Device Management setting in iOS Settings
Tap Apple Development:Figure 1.30: Apple Development section in Device Management settings
Tap Trust “Apple Development:Figure 1.31: Trust button
Tap Trust:Figure 1.32: Trust dialog box
You should see the following text, which shows the app is now trusted:
Figure 1.33: Apple Development section with trusted certificate
Click the Run button in Xcode to build and run again. You’ll see your app launch and run on your iOS device.Congratulations! You have successfully run your app on an actual iOS device!
In this chapter, you learned how to download and install Xcode on your Mac. Then, you familiarized yourself with the different parts of the Xcode user interface. After that, you created your first iOS app, selected a simulated iOS device, and built and ran the app in Simulator. Finally, you learned how to connect an iOS device to Xcode via USB so that you can run your app on it.
In the next chapter, we’ll start exploring the Swift language using Swift Playgrounds, and learn how simple values and types are implemented in Swift.
To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:
https://packt.link/8hBmp