Create, query, and edit a specific server version using a service geodatabase.

Use case
Workflows often progress in discrete stages, with each stage requiring the allocation of a different set of resources and business rules. Typically, each stage in the overall process represents a single unit of work, such as a work order or job. To manage these, you can create a separate, isolated version and modify it. Once this work is complete, you can integrate the changes into the default version.
How to use the sample
Once loaded, the map will zoom to the extent of the feature layer. The current version is indicated at the top of the map. Tap “Create” to open a dialog to specify the version information (name, description, and access). See the Additional information section for the restrictions on the version name.
Tap “Switch” to switch between the version you created and the default version. Edits will automatically be applied to your version when switching to the default version.
Select a feature to edit an attribute and/or tap a second time to relocate the feature.
How it works
- Create and load a
ServiceGeodatabasewith a feature service URL that has enabled Version Management. - Get the
ServiceFeatureTablefrom the service geodatabase. - Create a
FeatureLayerfrom the service feature table. - Create
ServiceVersionParameterswith a unique name,VersionAccess, and description.
- Note - See the Additional information section for more restrictions on the version name.
- Create a new version calling
ServiceGeodatabase.makeVersion(parameters:)passing in the service version parameters. - Switch to the version you have just created using
ServiceGeodatabase.switchToVersion(named:), passing in the version name obtained fromServiceVersionInforeturned from step above. - Select a
Featureto edit its “typdamage” attribute and location. - Apply these edits to your version by calling
ServiceGeodatabase.applyEdits(). - Switch back and forth between your version and the default version to see how the two versions differ.
Relevant API
- FeatureLayer
- ServiceFeatureTable
- ServiceGeodatabase
- ServiceVersionInfo
- ServiceVersionParameters
- VersionAccess
About the data
The feature layer used in this sample is Damage to commercial buildings located in Naperville, Illinois.
Additional information
Credentials:
- Username: editor01
- Password: S7#i2LWmYH75
The name of the version must meet the following criteria:
- Must not exceed 62 characters
- Must not include: Period (.), Semicolon (;), Single quotation mark (’), Double quotation mark (”)
- Must be unique
- Note - the version name will have the username and a period (.) prepended to it, e.g., “editor01.MyNewUniqueVersionName”.
Branch versioning access permission:
- Public - Any portal user can view and edit the version.
- Protected - Any portal user can view the version, but only the version owner, feature layer owner, and portal administrator can edit it.
- Private - Only the version owner, feature layer owner, and portal administrator can view and edit the version.
Tags
branch versioning, edit, version control, version management server
Sample code
// Copyright 2024 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 EditWithBranchVersioningView: View { /// The view model for the sample. @StateObject private var model = Model()
/// The placement of the callout for the selected feature. @State private var calloutPlacement: CalloutPlacement?
/// The parameters used to create a new version. @State private var versionParameters: ServiceVersionParameters?
/// The asynchronous action currently being preformed. @State private var selectedAction: AsyncAction? = .setUp
/// The point on the map to move the selected feature to. @State private var moveLocation: Point?
/// A Boolean value indicating whether the move confirmation alert is presented. @State private var isMovingFeature = false
/// A Boolean value indicating whether the create version parameters popover is presented. @State private var isCreatingVersion = false
/// A Boolean value indicating whether the switch version dialog is presented. @State private var isSwitchingVersion = false
/// A Boolean value indicating whether the set damage type dialog is presented. @State private var isSettingDamageType = false
/// The error shown in the error alert. @State private var error: (any Error)?
var body: some View { MapViewReader { mapViewProxy in MapView(map: model.map) .callout(placement: $calloutPlacement.animation(.default.speed(2))) { placement in let placeName = placement.geoElement?.attributes[.placeNameKey] as? String let damageType = placement.geoElement?.attributes[.damageTypeKey] as? String
HStack { VStack(alignment: .leading) { Text(placeName ?? "") .font(.headline) Text(damageType ?? "") .font(.callout) } editDamageTypeButton } .padding(5) } .onSingleTapGesture { screenPoint, mapPoint in if model.selectedFeature != nil && !model.onDefaultVersion { // Shows the move confirmation alert if there is already a feature selected. isMovingFeature = true moveLocation = mapPoint } else { // Identifies and selects the feature at the tap location. selectedAction = .selectFeature(screenPoint: screenPoint, mapPoint: mapPoint) } } .alert( "Confirm Move", isPresented: $isMovingFeature, presenting: moveLocation, actions: { mapPoint in Button("Cancel", role: .cancel) { calloutPlacement = nil model.clearSelection() } Button("Move") { model.selectedFeature?.geometry = mapPoint selectedAction = .updateFeature } }, message: { _ in Text("Do you want to move the selected feature?") } ) .task(id: selectedAction) { guard let selectedAction else { return } calloutPlacement = nil
do { switch selectedAction { case .setUp: try await model.setUp() case .makeVersion: let version = try await model.createVersion(parameters: versionParameters!) try await model.switchToVersion(named: version) case .switchToVersion(let version): try await model.switchToVersion(named: version) case .updateFeature: try await model.updateFeature() case .selectFeature(let screenPoint, let mapPoint): model.clearSelection()
// Identifies the feature on the feature layer at the tapped point. let result = try await mapViewProxy.identify( on: model.featureLayer, screenPoint: screenPoint, tolerance: 10 )
if let feature = result.geoElements.first as? Feature { model.selectFeature(feature) calloutPlacement = .geoElement(feature, tapLocation: mapPoint) } } } catch { self.error = error }
// Resets the selected action so an action of the same type can be run again. self.selectedAction = nil } } .overlay(alignment: .top) { Text("Version: \(model.serviceGeodatabase.versionName)") .multilineTextAlignment(.center) .frame(maxWidth: .infinity, alignment: .center) .padding(8) .background(.regularMaterial, ignoresSafeAreaEdges: .horizontal) } .toolbar { ToolbarItemGroup(placement: .bottomBar) { createVersionButton switchVersionButton } } .errorAlert(presentingError: $error) .onTeardown { model.tearDown() } }
/// The button for editing the damage type of the selected feature. private var editDamageTypeButton: some View { Button("Edit", systemImage: "pencil") { isSettingDamageType = true } .imageScale(.large) .labelStyle(.iconOnly) .disabled(model.onDefaultVersion) .confirmationDialog("Damage Type", isPresented: $isSettingDamageType, titleVisibility: .visible) { ForEach(DamageType.allCases, id: \.self) { damageType in Button(damageType.label) { model.selectedFeature?.setAttributeValue( damageType.rawValue, forKey: .damageTypeKey ) selectedAction = .updateFeature } } } message: { Text("Choose a damage type for the building.") } }
/// The button for creating a version. private var createVersionButton: some View { Button("Create") { isCreatingVersion = true } .popover(isPresented: $isCreatingVersion) { CreateVersionParametersView(model: model) { parameters in // Makes a new version with the created parameters. versionParameters = parameters selectedAction = .makeVersion } .presentationDetents([.fraction(0.5)]) .frame(idealWidth: 320, idealHeight: 200) } }
/// The button for switching the current version. private var switchVersionButton: some View { Button("Switch") { isSwitchingVersion = true } .disabled(model.existingVersionNames.count < 2) .confirmationDialog("Versions", isPresented: $isSwitchingVersion, titleVisibility: .visible) { ForEach(model.existingVersionNames, id: \.self) { versionName in Button(versionName) { selectedAction = .switchToVersion(version: versionName) } } } message: { Text("Choose a version to switch to.") } }}
/// An asynchronous action associated with the sample.private enum AsyncAction: Equatable { /// Sets up the sample. case setUp /// Makes a version with the current version parameters. case makeVersion /// Switches to a version with an associated version name. case switchToVersion(version: String) /// Select a feature identified from an associated screen and map point. case selectFeature(screenPoint: CGPoint, mapPoint: Point) /// Updates the selected feature in it's feature table. case updateFeature}
/// The damage type of a feature.private enum DamageType: String, CaseIterable { case destroyed, major, minor, affected, inaccessible, `default`
/// A human-readable label for the damage type. var label: String { switch self { case .destroyed: "Destroyed" case .major: "Major" case .minor: "Minor" case .affected: "Affected" case .inaccessible: "Inaccessible" case .default: "Default" } }}
private extension String { /// The key for a feature's damage type attribute. static let damageTypeKey = "typdamage" /// The key for a feature's place name attribute. static let placeNameKey = "placename"}
#Preview { NavigationStack { EditWithBranchVersioningView() }}// Copyright 2024 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 Foundation
extension EditWithBranchVersioningView { /// The view model for the sample. @MainActor final class Model: ObservableObject { /// The names of the versions added by the user. /// /// - Note: To get a full list of versions, use `ServiceGeodatabase.versions`. /// In this sample, only the default version and versions created in current session are shown. @Published private(set) var existingVersionNames: [String] = []
/// A map with a streets basemap. let map: Map = { let map = Map(basemapStyle: .arcGISStreets)
// Initially centers the map's viewpoint on Naperville, IL, USA. map.initialViewpoint = Viewpoint( center: Point(x: -9811970, y: 5127180, spatialReference: .webMercator), scale: 4e3 ) return map }()
/// A geodatabase connected to the damage assessment feature service. let serviceGeodatabase = ServiceGeodatabase(url: .damageAssessmentFeatureService)
/// The feature layer for displaying the damaged building features. private(set) var featureLayer: FeatureLayer!
/// The feature currently selected by the user. private(set) var selectedFeature: Feature?
/// A Boolean value indicating whether the geodatabase's current version it's default version. var onDefaultVersion: Bool { serviceGeodatabase.versionName == serviceGeodatabase.defaultVersionName }
/// Sets up the service geodatabase and feature layer. func setUp() async throws { // Adds the credential to access the feature service for the service geodatabase. try await ArcGISEnvironment.authenticationManager.arcGISCredentialStore.add(.publicSample)
try await serviceGeodatabase.load() existingVersionNames.append(serviceGeodatabase.defaultVersionName)
// Creates a feature layer from the geodatabase and adds it to the map. let serviceFeatureTable = serviceGeodatabase.table(withLayerID: 0)! featureLayer = FeatureLayer(featureTable: serviceFeatureTable) map.addOperationalLayer(featureLayer) }
/// Cleans up the model's setup. func tearDown() { ArcGISEnvironment.authenticationManager.arcGISCredentialStore.removeAll() }
/// Creates a new version in the service using given parameters. /// - Parameter parameters: The properties of the new version. /// - Returns: The name of the created version. func createVersion(parameters: ServiceVersionParameters) async throws -> String { let versionInfo = try await serviceGeodatabase.makeVersion(parameters: parameters) existingVersionNames.append(versionInfo.name) return versionInfo.name }
/// Switches the geodatabase version to a version with a given name. /// - Parameter versionName: The name of the version to connect to. func switchToVersion(named versionName: String) async throws { if onDefaultVersion { // Discards the local edits when on the default branch. // Making edits on default branch is disabled, but this is left here for parity. try await serviceGeodatabase.undoLocalEdits() } else { // Applies the local edits when on a user created branch. _ = try await serviceGeodatabase.applyEdits() } clearSelection()
try await serviceGeodatabase.switchToVersion(named: versionName) }
/// Selects a feature on the feature layer. func selectFeature(_ feature: Feature) { featureLayer.selectFeature(feature) selectedFeature = feature }
/// Clears the selected feature. func clearSelection() { featureLayer?.clearSelection() selectedFeature = nil }
/// Updates the selected feature in it's feature table. func updateFeature() async throws { guard let selectedFeature, let table = selectedFeature.table else { return } try await table.update(selectedFeature)
clearSelection() } }}
private extension URL { /// The URL to the damage assessment feature server. static var damageAssessmentFeatureService: URL { URL(string: "https://sampleserver7.arcgisonline.com/server/rest/services/DamageAssessment/FeatureServer")! }}
private extension ArcGISCredential { /// The public credentials for the data in this sample. /// - Note: Never hardcode login information in a production application. This is done solely for the sake of the sample. static var publicSample: ArcGISCredential { get async throws { try await TokenCredential.credential( for: .damageAssessmentFeatureService, username: "editor01", password: "S7#i2LWmYH75" ) } }}// Copyright 2024 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
extension EditWithBranchVersioningView { /// A view that creates service version parameters from user inputs. struct CreateVersionParametersView: View { /// The view model for the sample. @ObservedObject var model: Model
/// The action to perform when the parameters are created, i.e, when the "Done" button is pressed. let action: (ServiceVersionParameters) -> Void
/// The action to dismiss the view. @Environment(\.dismiss) private var dismiss
/// The name of the version entered by the user. @State private var versionName = ""
/// The description of the version entered by the user. @State private var versionDescription = ""
/// The version access for the version selected by the user. @State private var selectedVersionAccess: VersionAccess = .public
var body: some View { NavigationStack { Form { TextField("Name", text: $versionName) .autocorrectionDisabled() .textInputAutocapitalization(.never) .onChange(of: versionName) { // Ensures the inputted version name only contains valid characters. self.versionName = versionName.replacing(/[.;'"]/, with: "") }
TextField("Description", text: $versionDescription )
Picker("Access Permissions", selection: $selectedVersionAccess) { ForEach(VersionAccess.allCases, id: \.self) { versionAccess in Text(versionAccess.label) } } } .navigationTitle("New Version") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel", role: .cancel) { model.clearSelection() dismiss() } }
ToolbarItem(placement: .confirmationAction) { Button("Add") { let parameters = ServiceVersionParameters() parameters.access = selectedVersionAccess parameters.name = versionName parameters.description = versionDescription
action(parameters) dismiss() } .disabled( versionName.isEmpty || versionName.trimmingCharacters(in: .whitespacesAndNewlines).count > 62 ) } } } } }}
private extension VersionAccess { /// All the version access cases. static var allCases: [Self] { [.public, .protected, .private] }
/// A human-readable label for the version access. var label: String { switch self { case .public: "Public" case .protected: "Protected" case .private: "Private" @unknown default: "Unknown" } }}