Edit with branch versioning

View on GitHub

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

Image of Edit with branch versioning sample 1 Image of Edit with branch versioning sample 2

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

  1. Create and load a ServiceGeodatabase with a feature service URL that has enabled Version Management.
  2. Get the ServiceFeatureTable from the service geodatabase.
  3. Create a FeatureLayer from the service feature table.
  4. Create ServiceVersionParameters with a unique name, VersionAccess, and description.
  • Note - See the Additional information section for more restrictions on the version name.
  1. Create a new version calling ServiceGeodatabase.makeVersion(parameters:) passing in the service version parameters.
  2. Switch to the version you have just created using ServiceGeodatabase.switchToVersion(named:), passing in the version name obtained from ServiceVersionInfo returned from step above.
  3. Select a Feature to edit its "typdamage" attribute and location.
  4. Apply these edits to your version by calling ServiceGeodatabase.applyEdits().
  5. 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:

  1. Must not exceed 62 characters
  2. Must not include: Period (.), Semicolon (;), Single quotation mark ('), Double quotation mark (")
  3. 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:

  1. Public - Any portal user can view and edit the version.
  2. Protected - Any portal user can view the version, but only the version owner, feature layer owner, and portal administrator can edit it.
  3. 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

EditWithBranchVersioningView.swiftEditWithBranchVersioningView.swiftEditWithBranchVersioningView.Model.swiftEditWithBranchVersioningView.Views.swift
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
// 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 ArcGIS
import 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: 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)
    }

    /// 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()
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.