Create features from preset and group shared templates.

Use case
Preset and group shared templates support guided, repeatable, high-quality editing. Preset templates place predefined feature arrangements, while group templates create feature sets relative to a user-defined base geometry. By automatically applying attributes, symbology, geometry settings, and feature relationships or associations, they help field staff create consistent, fully configured assets with only a few choices.
How to use the sample
Open “Shared Templates” and select a template. When using a pointer, hover over a template to view its description. Tap on the map to place a point, or tap multiple positions to sketch a line. Once the sketch is valid, choose “Complete” to create features locally. Choose “Cancel” at any time while drawing to discard the sketch. Choose “Save” to send the local edits to the service, or “Undo” to discard all local edits. Resolve any pending local edits before selecting another template.
How it works
- Create a
Mapfrom a web map portal item and load it. - Get the first available
ServiceGeodatabasefrom the map’s operationalFeatureLayerobjects backed byServiceFeatureTableobjects. - Call
querySharedTemplates()without explicit query parameters. Visit the returned layers in ascending layer ID order and select the first preset and first group template encountered, displaying at most one of each kind overall. Store each selected template’s layer ID and display its name, kind, and swatch, with its description available as help text. - Call
makeSwatch(layerID:)to generate each template’s swatch image, falling back to a default image when a swatch is unavailable. - Call the selected template’s
defaultConstructionTool(forLayerWithID:). Set theGeometryEditortool to aVertexTool, then start the editor withPoint.selffor a.pointconstruction tool kind orPolyline.selffor.line. Report an error if the construction tool is unavailable or has an unsupported kind. - After the user selects “Complete”, verify that the geometry editor is started, capture its
geometry, and check that the geometry’ssketchIsValidis true. Callstop(), then pass the captured geometry tomakeFeatures(sharedTemplate:geometry:)to create a feature creation set. - Call
addFeatures(using:)to add the feature creation set to the geodatabase locally. - Select “Save” to apply local edits using
applyEdits(), or select “Undo” to discard them usingundoLocalEdits().
Relevant API
- GeometryConstructionTool
- GeometryEditor
- ServiceGeodatabase
- SharedTemplate
- SharedTemplateFeatureCreationSet
- SharedTemplateQueryParameters
- SharedTemplateSource
- VertexTool
About the data
The sample uses the Parks and Grounds Assets web map.
Tags
edit, feature, group, preset, shared template, shared template source, template
Sample code
// Copyright 2026 Esri//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.
import ArcGISimport SwiftUI
struct AddFeaturesWithSharedTemplatesView: View { /// The view model for the sample. @State private var model = Model()
/// The observed sketch validity. The geometry editor's change stream /// updates this state so SwiftUI refreshes the Complete button. @State private var canCompleteDrawing = false
/// Whether the shared templates popover is showing. @State private var templatePickerIsPresented = false
/// The requested editing operation, used as the editing task's identity. @State private var pendingGeodatabaseAction: EditingAction?
/// An error from loading templates, starting a sketch, or editing features /// that is presented in an alert. Task cancellation is not shown as an error. @State private var presentedError: (any Error)?
var body: some View { MapView(map: model.map) .geometryEditor(model.geometryEditor) .overlay(alignment: .top) { if !templatesAreUnavailable { statusOverlay } } .overlay { if templatesAreUnavailable { ContentUnavailableView( "No Templates", systemImage: "square.grid.2x2", description: Text( "This map has no preset or group shared templates." ) ) .background(.regularMaterial) } } .toolbar { ToolbarItemGroup(placement: .bottomBar) { if model.hasPendingEdits { editButtons } else if model.activeTemplateItem != nil { drawingButtons } else if !model.templateItems.isEmpty { sharedTemplatesButton } } } .task { do { try await model.setUp() } catch is CancellationError { // Do nothing. } catch { self.presentedError = error } } .task { for await geometry in model.geometryEditor.$geometry { canCompleteDrawing = geometry?.sketchIsValid ?? false } } .task(id: model.stateResetID) { guard let id = model.stateResetID else { return } await model.resetStateAfterDelay(for: id) } // Keep this task on the map view, not the conditional buttons. .task(id: pendingGeodatabaseAction) { guard let action = pendingGeodatabaseAction else { return } defer { pendingGeodatabaseAction = nil }
do { switch action { case .save: try await model.saveEdits() case .undo: try await model.undoEdits() case .complete: try await model.completeDrawing() } } catch is CancellationError { // Cancellation does not roll back submitted service edits. } catch { self.presentedError = error } } .onDisappear { // Do not replay a queued action when the view reappears. pendingGeodatabaseAction = nil if model.geometryEditor.isStarted { model.cancelDrawing() } } .errorAlert(presentingError: $presentedError) }
/// Whether loading succeeded without any supported templates. private var templatesAreUnavailable: Bool { model.state == .ready && model.templateItems.isEmpty }
/// The instructions and progress indicator displayed above the map. private var statusOverlay: some View { HStack { VStack { Text(statusText) if let instruction = nextStepInstruction { Text(instruction) } } .multilineTextAlignment(.center) .frame(maxWidth: .infinity)
if model.operationIsInProgress { ProgressView() } } .padding(8) .background(.regularMaterial, ignoresSafeAreaEdges: .horizontal) }
/// The localized presentation of the current workflow state. private var statusText: LocalizedStringKey { switch model.state { case .creatingFeatures: "Creating features…" case .creationFailed: "Unable to create or add features." case .drawingCanceled: "Draw canceled." case .drawingLine: "Sketch a line, then tap Complete or Cancel." case .drawingPoint: "Place a point, then tap Complete or Cancel." case .editsSaved: "Edits saved." case .editsUndone: "Edits undone." case .featuresAdded: "Features added." case .invalidGeometry: "Draw a valid geometry, then tap Complete or Cancel." case .loading: "Loading shared templates…" case .loadingFailed: "Unable to load templates." case .ready: templateInstruction case .savingEdits: "Saving edits…" case .savingFailed: "Unable to save edits." case .undoFailed: "Unable to undo edits." case .undoingEdits: "Undoing local edits…" } }
/// The next action after an editing operation, based on current edits. private var nextStepInstruction: LocalizedStringKey? { switch model.state { case .creationFailed, .editsSaved, .editsUndone, .featuresAdded, .savingFailed, .undoFailed: model.hasPendingEdits ? "Save or undo edits." : templateInstruction default: nil } }
/// The instruction shown while the template picker is available. private var templateInstruction: LocalizedStringKey { "Open Shared Templates and select a template to create features." }
/// A localized label for a shared template kind. /// - Parameter kind: The kind of shared template to describe. /// - Returns: The template kind's localized string key. private func kindLabel(for kind: SharedTemplate.Kind) -> LocalizedStringKey { switch kind { case .feature: "Feature" case .group: "Group" case .preset: "Preset" @unknown default: "Unknown" } }
/// The button that presents the shared template picker. private var sharedTemplatesButton: some View { Button("Shared Templates", systemImage: "square.grid.2x2") { templatePickerIsPresented = true } .popover(isPresented: $templatePickerIsPresented) { templatePickerContent .padding() .presentationCompactAdaptation(.popover) .frame(idealWidth: 320) } .disabled(model.operationIsInProgress || pendingGeodatabaseAction != nil) }
/// The available shared templates and their swatches. private var templatePickerContent: some View { VStack(alignment: .leading, spacing: 8) { ForEach(model.templateItems) { item in Button { do { try model.startDrawing(with: item) templatePickerIsPresented = false } catch { self.presentedError = error } } label: { HStack(spacing: 8) { TemplateSwatch(item: item)
VStack(alignment: .leading) { Text(item.template.name) .fontWeight(.semibold) Text(kindLabel(for: item.template.kind)) .font(.caption) }
Spacer() } .contentShape(.rect) } .buttonStyle(.plain) .help(item.template.description) .disabled(model.operationIsInProgress || pendingGeodatabaseAction != nil) } } }
/// The controls for saving or discarding local edits. private var editButtons: some View { Group { Button("Save") { pendingGeodatabaseAction = .save }
Spacer()
Button("Undo") { pendingGeodatabaseAction = .undo } } .disabled(model.operationIsInProgress || pendingGeodatabaseAction != nil) }
/// The controls for completing or canceling the current sketch. private var drawingButtons: some View { Group { if #available(iOS 26, *) { Button(role: .cancel) { model.cancelDrawing() } } else { Button("Cancel", systemImage: "xmark") { model.cancelDrawing() } .buttonStyle(.plain) }
Spacer()
if #available(iOS 26, *) { Button(role: .confirm) { pendingGeodatabaseAction = .complete } .disabled(!canCompleteDrawing) } else { Button("Done", systemImage: "checkmark") { pendingGeodatabaseAction = .complete } .disabled(!canCompleteDrawing) .buttonStyle(.plain) } } .disabled(model.operationIsInProgress || pendingGeodatabaseAction != nil) }}
private extension AddFeaturesWithSharedTemplatesView { /// A template's swatch, rendered when its picker row appears. struct TemplateSwatch: View { /// The template and target layer used to render the swatch. let item: Model.TemplateItem
/// The rendered swatch for the template. @State private var swatch: UIImage?
var body: some View { let image = if let swatch { Image(uiImage: swatch) } else { Image(systemName: "plus.square") } image .resizable() .scaledToFit() .frame(width: 36, height: 36) .accessibilityHidden(true) .task(id: item.id) { swatch = nil // A missing swatch should not prevent template selection. guard let swatch = try? await item.template .makeSwatch(layerID: item.layerID) else { return } self.swatch = swatch } } }
/// An editing operation requested by a toolbar button. enum EditingAction: Equatable { case save case undo case complete }}
extension AddFeaturesWithSharedTemplatesView.Model.SampleError: LocalizedError { var errorDescription: String? { switch self { case .sharedTemplateSourceNotFound: "The map does not contain a shared template source." case .unsupportedConstructionTool: "The template's default construction tool is not supported by this sample." } }}
#Preview { NavigationStack { AddFeaturesWithSharedTemplatesView() }}// Copyright 2026 Esri//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.
import ArcGISimport Foundationimport Observation
extension AddFeaturesWithSharedTemplatesView { /// The view model for the sample. @MainActor @Observable final class Model { /// A shared template and the ID of its target layer. struct TemplateItem: Identifiable { /// A unique identifier for the item. let id = UUID() /// The shared template represented by the item. let template: SharedTemplate /// The ID of a layer referenced by the template. let layerID: Int }
/// The current stage or outcome of the shared template workflow. enum WorkflowState { case creatingFeatures case creationFailed case drawingCanceled case drawingLine case drawingPoint case editsSaved case editsUndone case featuresAdded case invalidGeometry case loading case loadingFailed case ready case savingEdits case savingFailed case undoFailed case undoingEdits }
/// The Parks and Grounds Assets web map whose feature layers provide /// the shared templates used to create features in this sample. let map = Map( item: PortalItem( portal: .arcGISOnline(connection: .anonymous), id: PortalItem.ID("b635be46dfb545b888077389ac7f0962")! ) )
/// The geometry editor used to place a shared template's base geometry. let geometryEditor = GeometryEditor()
/// The shared templates displayed in the template picker. private(set) var templateItems: [TemplateItem] = []
/// The template currently being used to create features. private(set) var activeTemplateItem: TemplateItem?
/// Whether the geodatabase has edits to save or undo. private(set) var hasPendingEdits = false
/// The current workflow state, interpreted by the view. private(set) var state: WorkflowState = .loading { didSet { stateResetID = nil } }
/// Identifies a pending transition from canceled drawing to ready. private(set) var stateResetID: UUID?
/// Whether an asynchronous operation is in progress. private(set) var operationIsInProgress = false
/// The service geodatabase that provides the shared templates. private var serviceGeodatabase: ServiceGeodatabase?
/// Loads the map and its available preset and group shared templates. func setUp() async throws { guard state == .loading || state == .loadingFailed else { return }
state = .loading operationIsInProgress = true defer { operationIsInProgress = false }
do { try await map.load()
// Get the first service geodatabase from the feature layers. guard let featureLayer = map.operationalLayers.first(where: { $0 is FeatureLayer }) as! FeatureLayer?, let featureTable = featureLayer.featureTable as? ServiceFeatureTable, let serviceGeodatabase = featureTable.serviceGeodatabase else { throw SampleError.sharedTemplateSourceNotFound } self.serviceGeodatabase = serviceGeodatabase
let templatesByLayer = try await serviceGeodatabase .querySharedTemplates() try Task.checkCancellation() templateItems = makeTemplateItems( templatesByLayer: templatesByLayer ) state = .ready } catch { state = .loadingFailed throw error } }
/// Creates picker items for the first preset and group templates, /// visiting layers in ascending ID order. /// - Parameter templatesByLayer: The shared templates keyed by layer ID. /// - Returns: Picker items for the first available template of each supported kind, /// including their layer IDs. private func makeTemplateItems( templatesByLayer: [Int: [SharedTemplate]] ) -> [TemplateItem] { var includedKinds: Set<SharedTemplate.Kind> = [] var items: [TemplateItem] = []
for (layerID, templates) in templatesByLayer.sorted(by: { $0.key < $1.key }) { for template in templates { guard [.preset, .group].contains(template.kind), !includedKinds.contains(template.kind) else { continue } items.append( TemplateItem( template: template, layerID: layerID ) ) includedKinds.insert(template.kind) }
if includedKinds.count == 2 { break } } return items }
/// Starts drawing a geometry for a shared template. /// - Parameter item: The selected shared template item. func startDrawing(with item: TemplateItem) throws { guard !geometryEditor.isStarted else { return }
guard let constructionTool = item.template.defaultConstructionTool( forLayerWithID: item.layerID ) else { throw SampleError.unsupportedConstructionTool }
activeTemplateItem = item geometryEditor.tool = VertexTool()
switch constructionTool.kind { case .point: state = .drawingPoint geometryEditor.start(withType: Point.self) case .line: state = .drawingLine geometryEditor.start(withType: Polyline.self) default: activeTemplateItem = nil throw SampleError.unsupportedConstructionTool } }
/// Completes the drawing in the geometry editor and adds /// the features to the local service geodatabase. func completeDrawing() async throws { guard let activeTemplateItem, let serviceGeodatabase else { return } guard geometryEditor.isStarted, let geometry = geometryEditor.geometry, geometry.sketchIsValid else { state = .invalidGeometry return } geometryEditor.stop() self.activeTemplateItem = nil
operationIsInProgress = true state = .creatingFeatures defer { finishEditing() operationIsInProgress = false }
do { let featureCreationSet = try await serviceGeodatabase .makeFeatures( sharedTemplate: activeTemplateItem.template, geometry: geometry ) try Task.checkCancellation() try await serviceGeodatabase.addFeatures( using: featureCreationSet ) state = .featuresAdded } catch { state = .creationFailed throw error } }
/// Stops drawing and resets the template picker. func cancelDrawing() { if geometryEditor.isStarted { geometryEditor.stop() } activeTemplateItem = nil state = .drawingCanceled stateResetID = UUID() }
/// Returns to ready after two seconds unless the workflow changes. /// - Parameter id: The identifier of the pending state reset. func resetStateAfterDelay(for id: UUID) async { do { try await Task.sleep(for: .seconds(2)) } catch { return } guard !Task.isCancelled, stateResetID == id else { return } state = .ready }
/// Applies the local edits to the service. func saveEdits() async throws { guard let serviceGeodatabase else { return }
operationIsInProgress = true state = .savingEdits defer { finishEditing() operationIsInProgress = false }
do { let editResults = try await serviceGeodatabase.applyEdits() state = if editResults.allSatisfy({ $0.editResults.allSatisfy { !$0.didCompleteWithErrors } }) { .editsSaved } else { .savingFailed } } catch { state = .savingFailed throw error } }
/// Discards all local edits in the service geodatabase. func undoEdits() async throws { guard let serviceGeodatabase else { return }
operationIsInProgress = true state = .undoingEdits defer { finishEditing() operationIsInProgress = false }
do { try await serviceGeodatabase.undoLocalEdits() state = .editsUndone } catch { state = .undoFailed throw error } }
/// Reconciles state after an editing operation, even if it failed or was canceled. private func finishEditing() { hasPendingEdits = serviceGeodatabase?.hasLocalEdits ?? false activeTemplateItem = nil } }}
extension AddFeaturesWithSharedTemplatesView.Model { /// An error associated with the shared template workflow. enum SampleError: Error { case sharedTemplateSourceNotFound case unsupportedConstructionTool }}