Tải bản đầy đủ (.pdf) (566 trang)

SwiftUI Essentials iOS 14 Edition: Learn to Develop IOS Apps Using SwiftUI, Swift 5 and Xcode 12 by Neil Smyth

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (19.59 MB, 566 trang )


SwiftUIEssentials
iOS14Edition
SwiftUIEssentials–iOS14Edition
ISBN-13:978-1-951442-27-9
©2020NeilSmyth/PayloadMedia,Inc.AllRightsReserved.
This book is provided for personal use only. Unauthorized use, reproduction
and/ordistributionstrictlyprohibited.Allrightsreserved.
The content of this book is provided for informational purposes only. Neither
thepublishernortheauthoroffersanywarrantiesorrepresentation,expressor
implied,withregardtotheaccuracyofinformationcontainedinthisbook,nor
do they accept any liability for any loss or damage arising from any errors or
omissions.
Thisbookcontainstrademarkedtermsthatareusedsolelyforeditorialpurposes
andtothebenefitoftherespectivetrademarkowner.Thetermsusedwithinthis
bookarenotintendedasinfringementofanytrademarks.
Rev:1.0


TableofContents
1.StartHere
1.1ForSwiftProgrammers
1.2ForNon-SwiftProgrammers
1.3SourceCodeDownload
1.4Feedback
1.5Errata
2.JoiningtheAppleDeveloperProgram
2.1DownloadingXcode12andtheiOS14SDK
2.2AppleDeveloperProgram
2.3WhentoEnrollintheAppleDeveloperProgram?
2.4EnrollingintheAppleDeveloperProgram


2.5Summary
3.InstallingXcode12andtheiOS14SDK
3.1IdentifyingYourmacOSVersion
3.2InstallingXcode12andtheiOS14SDK
3.3StartingXcode
3.4AddingYourAppleIDtotheXcodePreferences
3.5DeveloperandDistributionSigningIdentities
3.6Summary
4.AnIntroductiontoXcode12Playgrounds
4.1WhatisaPlayground?
4.2CreatingaNewPlayground
4.3ASwiftPlaygroundExample
4.4ViewingResults
4.5AddingRichTextComments
4.6WorkingwithPlaygroundPages
4.7WorkingwithSwiftUIandLiveViewinPlaygrounds
4.8Summary
5.SwiftDataTypes,ConstantsandVariables
5.1UsingaSwiftPlayground
5.2SwiftDataTypes
5.2.1IntegerDataTypes
5.2.2FloatingPointDataTypes


5.2.3BoolDataType
5.2.4CharacterDataType
5.2.5StringDataType
5.2.6SpecialCharacters/EscapeSequences
5.3SwiftVariables
5.4SwiftConstants

5.5DeclaringConstantsandVariables
5.6TypeAnnotationsandTypeInference
5.7TheSwiftTuple
5.8TheSwiftOptionalType
5.9TypeCastingandTypeChecking
5.10Summary
6.SwiftOperatorsandExpressions
6.1ExpressionSyntaxinSwift
6.2TheBasicAssignmentOperator
6.3SwiftArithmeticOperators
6.4CompoundAssignmentOperators
6.5ComparisonOperators
6.6BooleanLogicalOperators
6.7RangeOperators
6.8TheTernaryOperator
6.9NilCoalescingOperator
6.10BitwiseOperators
6.10.1BitwiseNOT
6.10.2BitwiseAND
6.10.3BitwiseOR
6.10.4BitwiseXOR
6.10.5BitwiseLeftShift
6.10.6BitwiseRightShift
6.11CompoundBitwiseOperators
6.12Summary
7.SwiftControlFlow
7.1LoopingControlFlow
7.2TheSwiftfor-inStatement
7.2.1ThewhileLoop
7.3Therepeat...whileloop



7.4BreakingfromLoops
7.5ThecontinueStatement
7.6ConditionalControlFlow
7.7UsingtheifStatement
7.8Usingif...else…Statements
7.9Usingif...elseif...Statements
7.10TheguardStatement
7.11Summary
8.TheSwiftSwitchStatement
8.1WhyUseaswitchStatement?
8.2UsingtheswitchStatementSyntax
8.3ASwiftswitchStatementExample
8.4CombiningcaseStatements
8.5RangeMatchinginaswitchStatement
8.6Usingthewherestatement
8.7Fallthrough
8.8Summary
9.SwiftFunctions,MethodsandClosures
9.1WhatisaFunction?
9.2WhatisaMethod?
9.3HowtoDeclareaSwiftFunction
9.4ImplicitReturnsfromSingleExpressions
9.5CallingaSwiftFunction
9.6HandlingReturnValues
9.7LocalandExternalParameterNames
9.8DeclaringDefaultFunctionParameters
9.9ReturningMultipleResultsfromaFunction
9.10VariableNumbersofFunctionParameters

9.11ParametersasVariables
9.12WorkingwithIn-OutParameters
9.13FunctionsasParameters
9.14ClosureExpressions
9.15ShorthandArgumentNames
9.16ClosuresinSwift
9.17Summary
10.TheBasicsofSwiftObject-OrientedProgramming


10.1WhatisanInstance?
10.2WhatisaClass?
10.3DeclaringaSwiftClass
10.4AddingInstancePropertiestoaClass
10.5DefiningMethods
10.6DeclaringandInitializingaClassInstance
10.7InitializingandDe-initializingaClassInstance
10.8CallingMethodsandAccessingProperties
10.9StoredandComputedProperties
10.10LazyStoredProperties
10.11UsingselfinSwift
10.12UnderstandingSwiftProtocols
10.13OpaqueReturnTypes
10.14Summary
11.AnIntroductiontoSwiftSubclassingandExtensions
11.1Inheritance,ClassesandSubclasses
11.2ASwiftInheritanceExample
11.3ExtendingtheFunctionalityofaSubclass
11.4OverridingInheritedMethods
11.5InitializingtheSubclass

11.6UsingtheSavingsAccountClass
11.7SwiftClassExtensions
11.8Summary
12.AnIntroductiontoSwiftStructuresandEnumerations
12.1AnOverviewofSwiftStructures
12.2ValueTypesvs.ReferenceTypes
12.3WhentoUseStructuresorClasses
12.4AnOverviewofEnumerations
12.5Summary
13.AnIntroductiontoSwiftPropertyWrappers
13.1UnderstandingPropertyWrappers
13.2ASimplePropertyWrapperExample
13.3SupportingMultipleVariablesandTypes
13.4Summary
14.WorkingwithArrayandDictionaryCollectionsinSwift
14.1MutableandImmutableCollections


14.2SwiftArrayInitialization
14.3WorkingwithArraysinSwift
14.3.1ArrayItemCount
14.3.2AccessingArrayItems
14.4RandomItemsandShuffling
14.5AppendingItemstoanArray
14.5.1InsertingandDeletingArrayItems
14.6ArrayIteration
14.7CreatingMixedTypeArrays
14.8SwiftDictionaryCollections
14.9SwiftDictionaryInitialization
14.10Sequence-basedDictionaryInitialization

14.11DictionaryItemCount
14.12AccessingandUpdatingDictionaryItems
14.13AddingandRemovingDictionaryEntries
14.14DictionaryIteration
14.15Summary
15.UnderstandingErrorHandlinginSwift5
15.1UnderstandingErrorHandling
15.2DeclaringErrorTypes
15.3ThrowinganError
15.4CallingThrowingMethodsandFunctions
15.5AccessingtheErrorObject
15.6DisablingErrorCatching
15.7UsingthedeferStatement
15.8Summary
16.AnOverviewofSwiftUI
16.1UIKitandInterfaceBuilder
16.2SwiftUIDeclarativeSyntax
16.3SwiftUIisDataDriven
16.4SwiftUIvs.UIKit
16.5Summary
17.UsingXcodeinSwiftUIMode
17.1StartingXcode12
17.2CreatingaSwiftUIProject
17.3XcodeinSwiftUIMode


17.4ThePreviewCanvas
17.5PreviewPinning
17.6ThePreviewToolbar
17.7ModifyingtheDesign

17.8EditorContextMenu
17.9PreviewingonMultipleDeviceConfigurations
17.10RunningtheApponaSimulator
17.11RunningtheApponaPhysicaliOSDevice
17.12ManagingDevicesandSimulators
17.13EnablingNetworkTesting
17.14DealingwithBuildErrors
17.15MonitoringApplicationPerformance
17.16ExploringtheUserInterfaceLayoutHierarchy
17.17Summary
18.SwiftUIArchitecture
18.1SwiftUIAppHierarchy
18.2App
18.3Scenes
18.4Views
18.5Summary
19.TheAnatomyofaBasicSwiftUIProject
19.1CreatinganExampleProject
19.2ProjectFolders
19.3TheDemoProjectApp.swiftFile
19.4TheContentView.swiftFile
19.5Assets.xcassets
19.6Info.plist
19.7Summary
20.CreatingCustomViewswithSwiftUI
20.1SwiftUIViews
20.2CreatingaBasicView
20.3AddingAdditionalViews
20.4WorkingwithSubviews
20.5ViewsasProperties

20.6ModifyingViews
20.7WorkingwithTextStyles


20.8ModifierOrdering
20.9CustomModifiers
20.10BasicEventHandling
20.11BuildingCustomContainerViews
20.12WorkingwiththeLabelView
20.13Summary
21.SwiftUIStacksandFrames
21.1SwiftUIStacks
21.2Spacers,AlignmentandPadding
21.3ContainerChildLimit
21.4TextLineLimitsandLayoutPriority
21.5Traditionalvs.LazyStacks
21.6SwiftUIFrames
21.7FramesandtheGeometryReader
21.8Summary
22.SwiftUIStateProperties,Observable,StateandEnvironmentObjects
22.1StateProperties
22.2StateBinding
22.3ObservableObjects
22.4StateObjects
22.5EnvironmentObjects
22.6Summary
23.ASwiftUIExampleTutorial
23.1CreatingtheExampleProject
23.2ReviewingtheProject
23.3AddingaVStacktotheLayout

23.4AddingaSliderViewtotheStack
23.5AddingaStateProperty
23.6AddingModifierstotheTextView
23.7AddingRotationandAnimation
23.8AddingaTextFieldtotheStack
23.9AddingaColorPicker
23.10TidyingtheLayout
23.11Summary
24.SwiftUILifecycleEventModifiers
24.1CreatingtheLifecycleDemoProject


24.2DesigningtheApp
24.3TheonAppearandonDisappearModifiers
24.4TheonChangeModifier
24.5ScenePhaseandtheonChangeModifier
24.6Summary
25.SwiftUIObservableandEnvironmentObjects–ATutorial
25.1AbouttheObservableDemoProject
25.2CreatingtheProject
25.3AddingtheObservableObject
25.4DesigningtheContentViewLayout
25.5AddingtheSecondView
25.6AddingNavigation
25.7UsinganEnvironmentObject
25.8Summary
26.SwiftUIDataPersistenceusingAppStorageandSceneStorage
26.1The@SceneStoragePropertyWrapper
26.2The@AppStoragePropertyWrapper
26.3CreatingandPreparingtheStorageDemoProject

26.4UsingSceneStorage
26.5UsingAppStorage
26.6StoringCustomTypes
26.7Summary
27.SwiftUIStackAlignmentandAlignmentGuides
27.1ContainerAlignment
27.2AlignmentGuides
27.3UsingtheAlignmentGuidesTool
27.4CustomAlignmentTypes
27.5CrossStackAlignment
27.6ZStackCustomAlignment
27.7Summary
28.SwiftUIListsandNavigation
28.1SwiftUILists
28.2SwiftUIDynamicLists
28.3SwiftUINavigationViewandNavigationLink
28.4MakingtheListEditable
28.5HierarchicalLists


28.6Summary
29.ASwiftUIListandNavigationTutorial
29.1AbouttheListNavDemoProject
29.2CreatingtheListNavDemoProject
29.3PreparingtheProject
29.4AddingtheCarStructure
29.5LoadingtheJSONData
29.6AddingtheDataStore
29.7DesigningtheContentView
29.8DesigningtheDetailView

29.9AddingNavigationtotheList
29.10DesigningtheAddCarView
29.11ImplementingAddandEditButtons
29.12AddingtheEditButtonMethods
29.13Summary
30.AnOverviewofList,OutlineGroupandDisclosureGroup
30.1HierarchicalDataandDisclosures
30.2HierarchiesandDisclosureinSwiftUILists
30.3UsingOutlineGroup
30.4UsingDisclosureGroup
30.5Summary
31.ASwiftUIList,OutlineGroupandDisclosureGroupTutorial
31.1AbouttheExampleProject
31.2CreatingtheOutlineGroupDemoProject
31.3AddingtheDataStructure
31.4AddingtheListView
31.5TestingtheProject
31.6UsingtheSidebarListStyle
31.7UsingOutlineGroup
31.8WorkingwithDisclosureGroups
31.9Summary
32.BuildingSwiftUIGridswithLazyVGridandLazyHGrid
32.1SwiftUIGrids
32.2GridItems
32.3CreatingtheGridDemoProject
32.4WorkingwithFlexibleGridItems


32.5AddingScrollingSupporttoaGrid
32.6WorkingwithAdaptiveGridItems

32.7WorkingwithFixedGridItems
32.8UsingtheLazyHGridView
32.9Summary
33.BuildingTabbedandPagedViewsinSwiftUI
33.1AnOverviewofSwiftUITabView
33.2CreatingtheTabViewDemoApp
33.3AddingtheTabViewContainer
33.4AddingtheContentViews
33.5AddingViewPaging
33.6AddingtheTabItems
33.7AddingTabItemTags
33.8Summary
34.BuildingContextMenusinSwiftUI
34.1CreatingtheContextMenuDemoProject
34.2PreparingtheContentView
34.3AddingtheContextMenu
34.4TestingtheContextMenu
34.5Summary
35.BasicSwiftUIGraphicsDrawing
35.1CreatingtheDrawDemoProject
35.2SwiftUIShapes
35.3UsingOverlays
35.4DrawingCustomPathsandShapes
35.5DrawingGradients
35.6Summary
36.SwiftUIAnimationandTransitions
36.1CreatingtheAnimationDemoExampleProject
36.2ImplicitAnimation
36.3RepeatinganAnimation
36.4ExplicitAnimation

36.5AnimationandStateBindings
36.6AutomaticallyStartinganAnimation
36.7SwiftUITransitions
36.8CombiningTransitions


36.9AsymmetricalTransitions
36.10Summary
37.WorkingwithGestureRecognizersinSwiftUI
37.1CreatingtheGestureDemoExampleProject
37.2BasicGestures
37.3TheonChangeActionCallback
37.4TheupdatingCallbackAction
37.5ComposingGestures
37.6Summary
38.CreatingaCustomizedSwiftUIProgressView
38.1ProgressViewStyles
38.2CreatingtheProgressViewDemoProject
38.3AddingaProgressView
38.4UsingtheCircularProgressViewStyle
38.5DeclaringanIndeterminateProgressView
38.6ProgressViewCustomization
38.7Summary
39.AnOverviewofSwiftUIDocumentGroupScenes
39.1DocumentsinApps
39.2CreatingtheDocDemoApp
39.3TheDocumentGroupScene
39.4DeclaringFileTypeSupport
39.4.1DocumentContentTypeIdentifier
39.4.2HandlerRank

39.4.3TypeIdentifiers
39.4.4FilenameExtensions
39.4.5CustomTypeDocumentContentIdentifiers
39.4.6Exportedvs.ImportedTypeIdentifiers
39.5ConfiguringFileTypeSupportinXcode
39.6TheDocumentStructure
39.7TheContentView
39.8RunningtheExampleApp
39.9Summary
40.ASwiftUIDocumentGroupTutorial
40.1CreatingtheImageDocDemoProject
40.2ModifyingtheInfo.plistFile


40.3AddinganImageAsset
40.4ModifyingtheImageDocDemoDocument.swiftFile
40.5DesigningtheContentView
40.6FilteringtheImage
40.7TestingtheApp
40.8Summary
41.AnIntroductiontoSiriKit
41.1SiriandSiriKit
41.2SiriKitDomains
41.3SiriShortcuts
41.4SiriKitIntents
41.5HowSiriKitIntegrationWorks
41.6ResolvingIntentParameters
41.7TheConfirmMethod
41.8TheHandleMethod
41.9CustomVocabulary

41.10TheSiriUserInterface
41.11Summary
42.ASwiftUISiriKitMessagingExtensionTutorial
42.1CreatingtheExampleProject
42.2EnablingtheSiriEntitlement
42.3SeekingSiriAuthorization
42.4AddingtheIntentsExtension
42.5SupportedIntents
42.6TryingtheExample
42.7SpecifyingaDefaultPhrase
42.8ReviewingtheIntentHandler
42.9Summary
43.CustomizingtheSiriKitIntentUserInterface
43.1AddingtheIntentsUIExtension
43.2ModifyingtheUIExtension
43.3UsingtheconfigureMethod
43.4UsingtheconfigureViewMethod
43.5DesigningtheSiriSnippet
43.6ImplementingaconfigureViewMethod
43.7TestingtheExtension


43.8Summary
44.ASwiftUISiriKitNSUserActivityTutorial
44.1AbouttheSiriKitPhotoSearchProject
44.2CreatingtheSiriPhotoProject
44.3EnablingtheSiriEntitlement
44.4SeekingSiriAuthorization
44.5AddinganImageAsset
44.6AddingtheIntentsExtensiontotheProject

44.7ReviewingtheDefaultIntentsExtension
44.8ModifyingtheSupportedIntents
44.9ModifyingtheIntentHandlerImplementation
44.10ImplementingtheResolveMethods
44.11ImplementingtheConfirmationMethod
44.12HandlingtheIntent
44.13TestingtheApp
44.14AddingaDataClasstoSiriPhoto
44.15DesigningtheContentView
44.16AddingSupportedActivityTypestoSiriPhoto
44.17HandlingtheNSUserActivityObject
44.18TestingtheCompletedApp
44.19Summary
45.AnOverviewofSiriShortcutAppIntegration
45.1AnOverviewofSiriShortcuts
45.2AnIntroductiontotheIntentDefinitionFile
45.3AutomaticallyGeneratedClasses
45.4DonatingShortcuts
45.5TheAddtoSiriButton
45.6Summary
46.ASwiftUISiriShortcutTutorial
46.1AbouttheExampleApp
46.2AppGroupsandUserDefaults
46.3PreparingtheProject
46.4RunningtheApp
46.5EnablingSiriSupport
46.6SeekingSiriAuthorization
46.7AddingtheIntentsExtension



46.8AddingtheSiriKitIntentDefinitionFile
46.9AddingtheIntenttotheAppGroup
46.10ConfiguringtheSiriKitIntentDefinitionFile
46.11AddingIntentParameters
46.12DeclaringShortcutCombinations
46.13ConfiguringtheIntentResponse
46.14ConfiguringTargetMembership
46.15ModifyingtheIntentHandlerCode
46.16AddingtheConfirmMethod
46.17DonatingShortcutstoSiri
46.18TestingtheShortcuts
46.19DesigningtheIntentUI
46.20Summary
47.BuildingWidgetswithSwiftUIandWidgetKit
47.1AnOverviewofWidgets
47.2TheWidgetExtension
47.3WidgetConfigurationTypes
47.4WidgetEntryView
47.5WidgetTimelineEntries
47.6WidgetTimeline
47.7WidgetProvider
47.8ReloadPolicy
47.9Relevance
47.10ForcingaTimelineReload
47.11WidgetSizes
47.12WidgetPlaceholder
47.13Summary
48.ASwiftUIWidgetKitTutorial
48.1AbouttheWidgetDemoProject
48.2CreatingtheWidgetDemoProject

48.3BuildingtheApp
48.4AddingtheWidgetExtension
48.5AddingtheWidgetData
48.6CreatingSampleTimelines
48.7AddingImageandColorAssets
48.8DesigningtheWidgetView


48.9ModifyingtheWidgetProvider
48.10ConfiguringthePlaceholderView
48.11PreviewingtheWidget
48.12Summary
49.SupportingWidgetKitSizeFamilies
49.1SupportingMultipleSizeFamilies
49.2AddingSizeSupporttotheWidgetView
49.3Summary
50.ASwiftUIWidgetKitDeepLinkTutorial
50.1AddingDeepLinkSupporttotheWidget
50.2AddingDeepLinkSupporttotheApp
50.3TestingtheWidget
50.4Summary
51.AddingConfigurationOptionstoaWidgetKitWidget
51.1ModifyingtheWeatherData
51.2ConfiguringtheIntentDefinition
51.3ModifyingtheWidget
51.4TestingWidgetConfiguration
51.5CustomizingtheConfigurationIntentUI
51.6Summary
52.IntegratingUIViewswithSwiftUI
52.1SwiftUIandUIKitIntegration

52.2IntegratingUIViewsintoSwiftUI
52.3AddingaCoordinator
52.4HandlingUIKitDelegationandDataSources
52.5AnExampleProject
52.6WrappingtheUIScrolledView
52.7ImplementingtheCoordinator
52.8UsingMyScrollView
52.9Summary
53.IntegratingUIViewControllerswithSwiftUI
53.1UIViewControllersandSwiftUI
53.2CreatingtheViewControllerDemoproject
53.3WrappingtheUIImagePickerController
53.4DesigningtheContentView


53.5CompletingMyImagePicker
53.6CompletingtheContentView
53.7TestingtheApp
53.8Summary
54.IntegratingSwiftUIwithUIKit
54.1AnOverviewoftheHostingController
54.2AUIHostingControllerExampleProject
54.3AddingtheSwiftUIContentView
54.4PreparingtheStoryboard
54.5AddingaHostingController
54.6ConfiguringtheSegueAction
54.7EmbeddingaContainerView
54.8EmbeddingSwiftUIinCode
54.9Summary
55.PreparingandSubmittinganiOS14ApplicationtotheAppStore

55.1VerifyingtheiOSDistributionCertificate
55.2AddingAppIcons
55.3AssigntheProjecttoaTeam
55.4ArchivingtheApplicationforDistribution
55.5ConfiguringtheApplicationinAppStoreConnect
55.6ValidatingandSubmittingtheApplication
55.7ConfiguringandSubmittingtheAppforReview
Index


1.StartHere
ThegoalofthisbookistoteachtheskillsnecessarytobuildiOS14applications
usingSwiftUI,Xcode12andtheSwift5.3programminglanguage.
Beginningwiththebasics,thisbookprovidesanoutlineofthestepsnecessaryto
setupaniOSdevelopmentenvironmenttogetherwithanintroductiontotheuse
ofSwiftPlaygroundstolearnandexperimentwithSwift.
Thebookalsoincludesin-depthchaptersintroducingtheSwift5.3programming
language including data types, control flow, functions, object-oriented
programming,propertywrappersanderrorhandling.
An introduction to the key concepts of SwiftUI and project architecture is
followedbyaguidedtourofXcodeinSwiftUIdevelopmentmode.Thebookalso
covers the creation of custom SwiftUI views and explains how these views are
combinedtocreateuserinterfacelayoutsincludingtheuseofstacks,framesand
forms.
Othertopicscoveredincludedatahandlingusingstatepropertiesinadditionto
observable, state and environment objects, as are key user interface design
concepts such as modifiers, lists, tabbed views, context menus, user interface
navigation,andoutlinegroups.
The book also includes chapters covering graphics drawing, user interface
animation, view transitions and gesture handling, WidgetKit, document-based

appsandSiriKitintegration.
Chapters are also provided explaining how to integrate SwiftUI views into
existing UIKit-based projects and explains the integration of UIKit code into
SwiftUI.
Finally,thebookexplainshowtopackageupacompletedappanduploaditto
theAppStoreforpublication.
Along the way, the topics covered in the book are put into practice through
detailedtutorials,thesourcecodeforwhichisalsoavailablefordownload.
Theaimofthisbook,therefore,istoteachyoutheskillsnecessarytobuildyour
ownappsforiOS14usingSwiftUI.AssumingyouarereadytodownloadtheiOS
14 SDK and Xcode 12 and have an Apple Mac system you are ready to get
started.

1.1ForSwiftProgrammers
This book has been designed to address the needs of both existing Swift


programmersandthosewhoarenewtobothSwiftandiOSappdevelopment.If
youarefamiliarwiththeSwift5.3programminglanguage,youcanprobablyskip
the Swift specific chapters. If you are not yet familiar with the SwiftUI specific
language features of Swift, however, we recommend that you at least read the
sectionscoveringimplicitreturnsfromsingleexpressions,opaquereturntypesand
property wrappers. These features are central to the implementation and
understandingofSwiftUI.

1.2ForNon-SwiftProgrammers
IfyouarenewtoprogramminginSwiftthentheentirebookisappropriatefor
you.Juststartatthebeginningandkeepgoing.

1.3SourceCodeDownload

ThesourcecodeandXcodeprojectfilesfortheexamplescontainedinthisbook
areavailablefordownloadat:
/>
1.4Feedback
We want you to be satisfied with your purchase of this book. If you find any
errorsinthebook,orhaveanycomments,questionsorconcernspleasecontact
usat

1.5Errata
Whilewemakeeveryefforttoensuretheaccuracyofthecontentofthisbook,it
isinevitablethatabookcoveringasubjectareaofthissizeandcomplexitymay
include some errors and oversights. Any known issues with the book will be
outlined,togetherwithsolutionsatthefollowingURL:
/>Intheeventthatyoufindanerrornotlistedintheerrata,pleaseletusknowby
emailingourtechnicalsupportteamat


2.JoiningtheAppleDeveloperProgram
The first step in the process of learning to develop iOS 14 based applications
involves gaining an understanding of the advantages of enrolling in the Apple
DeveloperProgramanddecidingthepointatwhichitmakessensetopaytojoin.
With these goals in mind, this chapter will outline the costs and benefits of
joining the developer program and, finally, walk through the steps involved in
enrolling.

2.1DownloadingXcode12andtheiOS14SDK
ThelatestversionsofboththeiOSSDKandXcodecanbedownloadedfreeof
charge from the macOS App Store. Since the tools are free, this raises the
questionofwhethertoenrollintheAppleDeveloperProgram,ortowaituntilit
becomesnecessarylaterinyourappdevelopmentlearningcurve.


2.2AppleDeveloperProgram
Membership in the Apple Developer Program currently costs $99 per year to
enroll as an individual developer. Organization level membership is also
available.
PriortotheintroductionofiOS9andXcode7,oneofthekeyadvantagesofthe
developer program was that it permitted the creation of certificates and
provisioning profiles to test your applications on physical iOS devices.
Fortunately,thisisnolongerthecaseandallthatisnowrequiredtotestappson
physicaliOSdevicesisanAppleID.
Clearly much can be achieved without the need to pay to join the Apple
Developerprogram.Thereare,however,areasofappdevelopmentwhichcannot
be fully tested without program membership. Of particular significance is the
fact that Siri integration, iCloud access, Apple Pay, Game Center and In-App
Purchasing can only be enabled and tested with Apple Developer Program
membership.
OffurthersignificanceisthefactthatAppleDeveloperProgrammembershave
access to technical support from Apple’s iOS support engineers (though the
annualfeeinitiallycoversthesubmissionofonlytwosupportincidentreports,
more can be purchased). Membership also includes access to the Apple
Developer forums; an invaluable resource both for obtaining assistance and
guidancefromotheriOSdevelopers,andforfindingsolutionstoproblemsthat
othershaveencounteredandsubsequentlyresolved.


Programmembershipalsoprovidesearlyaccesstothepre-releaseBetaversions
ofXcode,macOSandiOS.
By far the most important aspect of the Apple Developer Program is that
membershipisamandatoryrequirementinordertopublishanapplicationfor
saleordownloadintheAppStore.

Clearly,programmembershipisgoingtoberequiredatsomepointbeforeyour
applicationreachestheAppStore.Theonlyquestionremainingiswhenexactly
tosignup.

2.3WhentoEnrollintheAppleDeveloperProgram?
Clearly,therearemanybenefitstoAppleDeveloperProgrammembershipand,
eventually, membership will be necessary to begin selling your apps. As to
whether to pay the enrollment fee now or later will depend on individual
circumstances.IfyouarestillintheearlystagesoflearningtodevelopiOSapps
orhaveyettocomeupwithacompellingideaforanapptodevelopthenmuch
ofwhatyouneedisprovidedwithoutprogrammembership.Asyourskilllevel
increasesandyourideasforappstodeveloptakeshapeyoucan,afterall,always
enrollinthedeveloperprogramlater.
If,ontheotherhand,youareconfidentthatyouwillreachthestageofhavingan
applicationreadytopublish,orknowthatyouwillneedaccesstomoreadvanced
featuressuchasSirisupport,iCloudstorage,In-AppPurchasingandApplePay
thenitisworthjoiningthedeveloperprogramsoonerratherthanlater.

2.4EnrollingintheAppleDeveloperProgram
If your goal is to develop iOS apps for your employer, then it is first worth
checking whether the company already has membership. That being the case,
contacttheprogramadministratorinyourcompanyandaskthemtosendyou
aninvitationfromwithintheAppleDeveloperProgramMemberCentertojoin
the team. Once they have done so, Apple will send you an email entitled You
Have Been Invited to Join an Apple Developer Program containing a link to
activate your membership. If you or your company is not already a program
member,youcanenrollonlineat:
/>Apple provides enrollment options for businesses and individuals. To enroll as
anindividual,youwillneedtoprovidecreditcardinformationinordertoverify
your identity. To enroll as a company, you must have legal signature authority

(oraccesstosomeonewhodoes)andbeabletoprovidedocumentationsuchasa


Dun&BradstreetD-U-N-Snumberanddocumentationconfirminglegalentity
status.
Acceptanceintothedeveloperprogramasanindividualmembertypicallytakes
less than 24 hours with notification arriving in the form of an activation email
fromApple.Enrollmentasacompanycantakeconsiderablylonger(sometimes
weeks or even months) due to the burden of the additional verification
requirements.
WhileawaitingactivationyoumaylogintotheMemberCenterwithrestricted
accessusingyourAppleIDandpasswordatthefollowingURL:
/>Once logged in, clicking on the Your Account tab at the top of the page will
displaytheprevailingstatusofyourapplicationtojointhedeveloperprogramas
EnrollmentPending.Oncetheactivationemailhasarrived,logintotheMember
Centeragainandnotethataccessisnowavailabletoawiderangeofoptionsand
resourcesasillustratedinFigure2-1

Figure2-1

2.5Summary
AnimportantearlystepintheiOS14applicationdevelopmentprocessinvolves
identifyingthebesttimetoenrollintheAppleDeveloperProgram.Thischapter
has outlined the benefits of joining the program, provided some guidance to
keep in mind when considering developer program membership and walked
brieflythroughtheenrollmentprocess.Thenextstepistodownloadandinstall
theiOS14SDKandXcode12developmentenvironment.


3.InstallingXcode12andtheiOS14

SDK
iOS apps are developed using the iOS SDK in conjunction with Apple’s Xcode
development environment. Xcode is an integrated development environment
(IDE)withinwhichyouwillcode,compile,testanddebugyouriOSapplications.
AlloftheexamplesinthisbookarebasedonXcodeversion12.2andmakeuseof
featuresunavailableinearlierXcodeversions.Inthischapterwewillcoverthe
stepsinvolvedininstallingbothXcode12.2andtheiOS14SDKonmacOS.

3.1IdentifyingYourmacOSVersion
When developing with SwiftUI, the Xcode 12.2 environment requires a system
runningmacOSBigSur(version11.0)orlater.Ifyouareunsureoftheversionof
macOS on your Mac, you can find this information by clicking on the Apple
menuinthetopleft-handcornerofthescreenandselectingtheAboutThisMac
optionfromthemenu.IntheresultingdialogchecktheVersionline.
If the “About This Mac” dialog does not indicate that macOS 11.0 or later is
running, click on the Software Update… button to download and install the
appropriateoperatingsystemupgrades.

Figure3-1

3.2InstallingXcode12andtheiOS14SDK
The best way to obtain the latest versions of Xcode and the iOS SDK is to
downloadthemfromtheAppleMacAppStore.LaunchtheAppStoreonyour


macOSsystem,enterXcodeintothesearchboxandclickontheGetbuttonto
initiatetheinstallation.ThiswillinstallbothXcodeandtheiOSSDK.

3.3StartingXcode
HavingsuccessfullyinstalledtheSDKandXcode,thenextstepistolaunchitso

thatwearereadytostartdevelopmentwork.TostartupXcode,openthemacOS
FinderandsearchforXcode.Sinceyouwillbemakingfrequentuseofthistool
takethisopportunitytodraganddropitontoyourdockforeasieraccessinthe
future. Click on the Xcode icon in the dock to launch the tool. The first time
Xcoderunsyoumaybepromptedtoinstalladditionalcomponents.Followthese
steps,enteringyourusernameandpasswordwhenpromptedtodoso.
OnceXcodehasloaded,andassumingthisisthefirsttimeyouhaveusedXcode
onthissystem,youwillbepresentedwiththeWelcomescreenfromwhichyou
arereadytoproceed:

Figure3-2

3.4AddingYourAppleIDtotheXcodePreferences
Regardless of whether or not you choose to enroll in the Apple Developer
ProgramitisworthaddingyourAppleIDtoXcodenowthatitisinstalledand
running.SelecttheXcode->Preferences…menuoptionfollowedbytheAccounts
tab. On the Accounts screen, click on the + button highlighted in Figure 3-3,
selectAppleIDfromtheresultingpanelandclickontheContinuebutton.When
prompted, enter your Apple ID and password before clicking on the Sign In
buttontoaddtheaccounttothepreferences.


×