29,99 €
Want to turn your app idea into reality? iOS 18 Programming for Beginners is a guide that revolves around building a journal app, designed to teach you practical iOS development skills from the ground up. Through this approach, you'll gain hands-on experience with Xcode programming and progress through building a UI and filling it with functionality.
Starting with the fundamentals of Swift 6, you'll learn how to construct user interfaces using storyboards and segues before diving into essential iOS concepts like table views, data handling, and map integration. The step-by-step tutorials guide you through key tasks such as persisting data with JSON, creating custom views, and integrating media into your apps. You’ll also discover how to enhance your apps using Apple Intelligence, incorporating machine learning and smart features to create cutting-edge iOS applications. The final chapters focus on crucial aspects of app development, including Swift Testing to ensure your app is robust, and submitting your app to the App Store—demystifying the journey from development to deployment.
Whether you're a beginner or transitioning to iOS development, this guide will equip you with the skills needed to create and publish your own apps.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 528
Veröffentlichungsjahr: 2024
iOS 18 Programming for Beginners
Ninth Edition
Learn iOS development with Swift 6, Xcode 16, and iOS 18 – your path to App Store success
Ahmad Sahar
iOS 18 Programming for Beginners
Ninth Edition
Copyright © 2024 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: Swaroop Singh
Project Editor: K. Loganathan
Content Development Editor: Matthew Davies
Copy Editor: Safis Editing
Technical Editor: Simanta Rajbangshi
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Presentation Designer: Rajesh Shirsath
Developer Relations Marketing Executive: Sohini Ghosh
First published: December 2016
Second edition: January 2018
Third edition: December 2018
Fourth edition: January 2020
Fifth edition: November 2020
Sixth edition: December 2021
Seventh edition: November 2022
Eighth edition: October 2023
Ninth edition: November 2024
Production reference: 1041224
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-83620-489-3
www.packt.com
Ahmad Sahar is a trainer, presenter, and consultant at Tomafuwi Productions. He is an Apple Certified Trainer for app development in Swift, and he has conducted training courses on for over ten years iOS mobile application development, Flutter mobile application development, and how to use Apple software and hardware. He also currently holds App Development with Swift Associate and Certified User certifications.
He is a member of the DevCon iOS online community in Malaysia and has conducted presentations and talks for this group. 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.
Ian Lockett is a mobile application developer with over 18 years of experience in the software industry. He has spent the last decade developing iOS and Android apps for a wide range of clients and industries. Most of Ian’s experience is in iOS development using Swift and Objective-C, but he has also created and maintained Android apps over the last few years using Kotlin.
Ian prides himself on attention to detail and delivering high-quality software. Ian lives in the UK with his wife and two children and now works for a large finance company having worked as a freelance/contract developer for the past seven years.
Read this book alongside other users, experts, and the author himself. 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/ios-Swift
Preface
Who this book is for
What this book covers
To get the most out of this book
Code in Action
Get in touch
Leave a review!
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 Build section
Running your app on an iOS device
Trusting the Developer App certificate on your iOS device
Summary
Join us on Discord!
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
Join us on Discord!
Conditionals and Optionals
Technical requirements
Introducing conditionals
Using if statements
Using switch statements
Introducing optionals and optional binding
Summary
Join us on Discord!
Range Operators and Loops
Technical requirements
Exploring range operators
Exploring loops
The for-in loop
The while loop
The repeat-while loop
Summary
Join us on Discord!
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
Join us on Discord!
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
Join us on Discord!
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
Join us on Discord!
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
Join us on Discord!
Swift Concurrency
Technical requirements
Understanding Swift concurrency
Examining an app without concurrency
Updating the app using async/await
Improving efficiency using async-let
Summary
Leave a review!
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 Xcode
Summary
Join us on Discord!
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
Join us on Discord!
Finishing Up Your User Interface
Technical requirements
Implementing the Journal Entry Detail screen
Implementing the Map screen
Summary
Join us on Discord!
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
Leave a review!
Part 3: Code
Getting Started with MVC and Table Views
Technical requirements
Understanding the MVC 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
Join us on Discord!
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
Join us on Discord!
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
Join us on Discord!
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
Join us on Discord!
Getting Started with JSON Files
Technical requirements
Creating a singleton
Modifying the JournalEntry class to be JSON-compatible
Loading and saving JSON data
Summary
Join us on Discord!
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
Join us on Discord!
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
Join us on Discord!
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
Join us on Discord!
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 UI 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
Leave a review!
Part 4: Features
Getting Started with SwiftData
Technical requirements
Introducing SwiftData
Modifying the JournalEntry class
Implementing SwiftData components
Modifying the JournalListViewController class
Summary
Join us on Discord!
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
Join us on Discord!
Getting Started with Swift Testing
Technical requirements
Introducing Swift Testing
Adding a Unit Testing target to your app
Writing tests for the JournalEntry class
Testing the JournalEntry class
Summary
Join us on Discord!
Getting Started with Apple Intelligence
Technical requirements
Introducing Apple Intelligence
Using predictive code completion in Xcode
Implementing Writing Tools in your app
Summary
Join us on Discord!
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
Leave a review!
Other Books You May Enjoy
Index
Cover
Index
Welcome to iOS 18 Programming for Beginners. This book is the ninth edition of the iOS Programming for Beginners series, and has been fully updated for iOS 18, macOS 15.0 Sequioa, and Xcode 16.
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 an 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 18 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 learn how to test your code using Swift Testing, and how to bring Apple Intelligence features into your apps.
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 that 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 them 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, covers 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 add annotations to 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 a 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 Swift Testing, teaches you how to test your code using Swift Testing.
Chapter 26, Getting Started with Apple Intelligence, shows you how to add Apple Intelligence features to your app.
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 18, macOS 15.0 Sequioa, Xcode 16, and Swift 6. Part 4 of this book also covers the latest technologies introduced by Apple during WWDC 2024, which are SwiftData, SwiftUI, Swift Testing, and Apple Intelligence.
To complete all the exercises in this book, you will need:
A Mac computer running macOS 14.0 Sonoma, macOS 15.0 Sequioa, or laterXcode 16.0 or laterTo check if your Mac supports macOS 15.0 Sequioa, see this link: https://www.apple.com/my/macos/macos-sequoia-preview/. 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.
The following chapter requires a paid Apple Developer account: Chapter 27, Testing and Submitting Your App to the App Store. Instructions on how to get a paid Apple Developer account are included.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/iOS-18-Programming-for-Beginners-Ninth-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=PLeLcvrwLe185EJSoURfHhSHfbPFkiZl6m
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/9781836204893.
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:
letcatAnimal() cat.name"Cat"cat.sound"Mew"cat.numberOfLegs4cat.breathesOxygentrueprint(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.
Thank you for purchasing this book from Packt Publishing—we hope you enjoy it! Your feedback is invaluable and helps us improve and grow. Once you’ve completed reading it, please take a moment to leave an Amazon review; it will only take a minute, but it makes a big difference for readers like you.
https://packt.link/r/1836204892
Scan the QR code below or visit the link to receive a free ebook of your choice.
https://packt.link/NzOWQ
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 below:https://packt.link/free-ebook/9781836204893
Submit your proof of purchase.That’s it! We’ll send your free PDF and other benefits to your email directly.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 6, 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 18 Programming for Beginners. I hope you will find this a useful introduction to creating and publishing iOS 18 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 it 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 14 Sonoma or macOS 15 SequoiaAn Apple Account (if you don’t have one, you will create one in this chapter)Optionally, an iOS device running iOS 18The 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-18-Programming-for-Beginners-Ninth-Edition
Check out the following video to see the code in action:
https://youtu.be/g3mNosIoR8E
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 total size of the download is very large (2.98 GB for Xcode and 8.36 GB for iOS 18 Simulator), 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 on your Mac prior to writing your first app. Follow these steps:
On your Mac, 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 Account, type it in the text field and enter your password when prompted. If you don’t have one, click the Create Apple Account button and follow the step-by-step instructions to create one:Figure 1.1: Apple account creation dialog box
You can see more information on how to create an Apple Account using this link: https://support.apple.com/en-us/108647#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. Tick iOS 18.0, leave all other options unticked, and click Download & Install:Figure 1.4: Development platforms screen
Xcode will prompt you to relaunch to use updated frameworks. Click Relaunch Xcode:Figure 1.5: Relaunch Xcode prompt
You’ll see a What’s New in Xcode screen. Click Continue:fFigure 1.6: What’s New in Xcode screen
You’ll see the Welcome to Xcode screen. Click Create New Project... in the left-hand pane:Figure 1.7: Welcome to Xcode screen
Xcode will start to download iOS 18.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: New project screen
You’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 the 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.Testing System: The testing system you will use. You will learn about this in Chapter 25,Getting Started with Swift Testing. Set it to None for now.Leave the other settings at their default values. 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.11: Save dialog box
You’ll see a dialog box saying Git Repository Creation Failed. Click 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 Xcode.Library button (2) – Displays user interface elements, code snippets, and other resources.Inspector button (3) – Used to display and hide the Inspector area.Don’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 downloaded and installed after 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
In your own projects, you should pick whichever simulator you require. That said, if you want to match the screenshots in this book exactly, use the iPhone SE (3rd generation) simulator. This simulator also has a home button, so it is easier to get to the home screen.
Figure 1.17: Simulator displaying your app
Switch back to Xcode and click on the Stopbutton (or press Command + .) to stop the currently running project.You have just created and run your first iOS app in Simulator! Great job!
The Destination menu has a section showing physical devices connected to your Mac and a Build section. You may be wondering what they 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 a section showing physical devices connected to your Mac, and a Build section.
These allow you to run apps on actual Mac or iOS devices and prepare apps for submission to the App Store.
Click the Destination menu in the toolbar to see the physical device and Build sections at the top of the menu:
Figure 1.18: Xcode Destination menu showing device and Build sections
If you have an Apple Silicon Mac, the physical device 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 Account (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 Account 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 Mac will display an Allow Accessory to Connect alert. Click Allow.Your iOS device will display a Trust This Computer alert. Tap Trust and key in your device passcode when prompted. Your iOS device is now connected to your Mac and will appear in Xcode’s Destination menu.Choose Window | Devices and Simulators in the Xcode menu bar. You will see a window displaying a message saying Developer Mode disabled:Figure 1.19: Xcode Devices and Simulators window showing Developer Mode disabled
Developer Mode was introduced by Apple during their Worldwide Developers 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: Privacy & Security screen showing Developer Mode
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 Enable and entering your iOS device’s passcode.The Devices and Simulators window will display a Preparing iPhone message. Wait a few minutes, then verify that the Devices and Simulators window no longer displays the Developer Mode disabled text:Figure 1.22: Xcode Devices and Simulators window showing Preparing iPhone message
Your iOS device is now ready to install and run apps from Xcode.
In Xcode, choose your iOS device from the Destination menu.Run the project by clicking the Run button (or use Command + R). You will get the following error in Xcode’s Signing & Capabilities panel: 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 Account 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 the Add Account… button selected
The Xcode Settings window appears with the Accounts pane selected. Enter your Apple Account and click Next:Figure 1.25: Apple Account creation dialog box
Note that you can create a different Apple Account 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.myname6712.JRNL.Build and run your app. If you are prompted for a password, enter your Mac’s login password and click Always Allow.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 Settings
Tap your Apple Account:Figure 1.30: Your Apple Account in Device Management settings
Tap Trust:Figure 1.31: Trust button
Tap Allow:Figure 1.32: Allow dialog box
You should see the following text, which shows the app is now trusted:
Figure 1.33: Device management 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.
Read this book alongside other users, experts, and the author himself. 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/ios-Swift