Edit and sync features with feature service

View on GitHub

Synchronize offline edits with a feature service.

Image of Edit and sync features with feature service sample

Use case

A survey worker who works in an area without an internet connection could take a geodatabase of survey features offline at their office, make edits and add new features to the offline geodatabase in the field, and sync the updates with the online feature service after returning to the office.

How to use the sample

Pan and zoom to position the red rectangle around the area you want to take offline. Tap "Generate Geodatabase" to take the area offline. When complete, the map will update to only show the offline area. To edit features, tap on a feature to select it and tap again anywhere else on the map to move the selected feature to the tapped location. To sync the edits with the feature service, tap the "Sync Geodatabase" button.

How it works

  1. Create a GeodatabaseSyncTask from a URL to a feature service.
  2. Create the default GenerateGeodatabaseParameters using GeodatabaseSyncTask.makeDefaultGenerateGeodatabaseParameters(extent:), passing in an Envelope extent.
  3. Create a GenerateGeodatabaseJob using GeodatabaseSyncTask.makeGenerateGeodatabaseJob(parameters:downloadFileURL:), passing in the parameters and a path to where the geodatabase should be downloaded locally.
  4. Start the job and get the result Geodatabase.
  5. To enable editing, load the geodatabase and get its feature tables. Create feature layers from the feature tables and add them to the map's operational layers collection.
  6. Create the default SyncGeodatabaseParameters using GeodatabaseSyncTask.makeDefaultSyncGeodatabaseParameters(geodatabase:syncDirection:).
  7. Create a SyncGeodatabaseJob from GeodatabaseSyncTask using makeSyncGeodatabaseJob(parameters:geodatabase:) passing in the parameters and geodatabase as arguments.
  8. Start the sync job to synchronize the edits.

Relevant API

  • FeatureLayer
  • FeatureTable
  • GenerateGeodatabaseJob
  • GenerateGeodatabaseParameters
  • GeodatabaseSyncTask
  • SyncGeodatabaseJob
  • SyncGeodatabaseParameters
  • SyncLayerOption

Offline data

This sample uses a San Francisco offline basemap tile package.

About the data

The basemap uses an offline tile package of San Francisco. The online feature service has features with wildfire information.

Tags

feature service, geodatabase, offline, synchronize

Sample Code

EditAndSyncFeaturesWithFeatureServiceView.swiftEditAndSyncFeaturesWithFeatureServiceView.swiftEditAndSyncFeaturesWithFeatureServiceView.Model.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
// 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 EditAndSyncFeaturesWithFeatureServiceView: View {
    /// The view model for the sample.
    @StateObject private var model = Model()

    /// The asynchronous action currently being preformed.
    @State private var selectedAction: AsyncAction? = .setUpMap

    /// The text describing the status of the sample.
    @State private var statusText = ""

    /// The error shown in the error alert.
    @State private var error: Error?

    var body: some View {
        GeometryReader { geometryProxy in
            MapViewReader { mapViewProxy in
                MapView(map: model.map)
                    .interactionModes(
                        // Disables the map when a geodatabase has been generated.
                        model.geodatabase == nil ? [.all] : []
                    )
                    .onSingleTapGesture { screenPoint, mapPoint in
                        guard model.geodatabase != nil else { return }

                        selectedAction = model.selectedFeature == nil
                        ? .selectFeature(screenPoint: screenPoint)
                        : .moveSelectedFeature(mapPoint: mapPoint)
                    }
                    .task(id: selectedAction) {
                        // Performs the selected action.
                        guard let action = selectedAction else { return }

                        do {
                            switch action {
                            case .setUpMap:
                                statusText = "Loading feature layers…"
                                try await model.setUpMap()
                                statusText = action.completionMessage
                            case .generateGeodatabase:
                                // Creates an envelope from the area of interest.
                                let viewRect = geometryProxy.frame(in: .local).inset(
                                    by: UIEdgeInsets(
                                        top: 20,
                                        left: geometryProxy.safeAreaInsets.leading + 20,
                                        bottom: 44,
                                        right: -geometryProxy.safeAreaInsets.trailing + 20
                                    )
                                )
                                guard let extent = mapViewProxy.envelope(
                                    fromViewRect: viewRect
                                ) else { return }

                                // Generates the geodatabase using the envelope.
                                try await model.generateGeodatabase(extent: extent)
                                statusText = action.completionMessage
                            case .selectFeature(let screenPoint):
                                // Identifies and selects a feature at the tapped screen point.
                                let identifyLayerResults = try await mapViewProxy.identifyLayers(
                                    screenPoint: screenPoint,
                                    tolerance: 22,
                                    maximumResultsPerLayer: 1
                                )

                                model.selectFeature(identifyLayerResults: identifyLayerResults)
                                if model.selectedFeature != nil {
                                    statusText = action.completionMessage
                                }
                            case .moveSelectedFeature(mapPoint: let mapPoint):
                                try await model.moveSelectedFeature(point: mapPoint)
                                statusText = action.completionMessage
                            case .sync:
                                try await model.syncGeodatabase()
                                statusText = action.completionMessage
                            case .cancelJob:
                                await model.cancelJob()
                                statusText = action.completionMessage
                            case .reset:
                                await model.reset()
                                await mapViewProxy.setViewpoint(model.map.initialViewpoint!)
                                selectedAction = .setUpMap
                                return
                            }
                        } catch {
                            self.error = error
                        }

                        selectedAction = nil
                    }
                    .errorAlert(presentingError: $error)
            }
        }
        .overlay(alignment: .top) {
            VStack {
                Text(statusText)
                    .multilineTextAlignment(.center)
                    .frame(maxWidth: .infinity, alignment: .center)
                    .padding(8)
                    .background(.regularMaterial, ignoresSafeAreaEdges: .horizontal)

                // The red rectangle representing the extent of data to include in the geodatabase.
                Rectangle()
                    .stroke(.red, lineWidth: 2)
                    .padding(EdgeInsets(top: 20, leading: 20, bottom: 44, trailing: 20))
                    .opacity(model.geodatabase == nil ? 1 : 0)
            }
        }
        .toolbar {
            ToolbarItemGroup(placement: .bottomBar) {
                Button("Reset") {
                    selectedAction = .reset
                }
                .disabled(model.geodatabase == nil)

                if model.geodatabase == nil {
                    Button("Generate Geodatabase") {
                        selectedAction = .generateGeodatabase
                    }
                } else {
                    Button("Sync Geodatabase") {
                        selectedAction = .sync
                    }
                    .disabled(!(model.geodatabase?.hasLocalEdits ?? false))
                }
            }
        }
        .disabled(selectedAction != nil)
        .overlay(alignment: .center) {
            // Shows a progress view when there is a job currently running.
            if let progress = model.currentJob?.progress {
                VStack {
                    Text(selectedAction == .generateGeodatabase
                         ? "Creating geodatabase…"
                         : "Syncing geodatabase…"
                    )
                    .padding(.bottom)

                    ProgressView(progress)
                        .frame(maxWidth: 180)

                    Button("Cancel") {
                        selectedAction = .cancelJob
                    }
                    .disabled(selectedAction == .cancelJob)
                }
                .padding()
                .background(.ultraThickMaterial)
                .clipShape(.rect(cornerRadius: 10))
                .shadow(radius: 50)
            }
        }
        .onDisappear {
            // Cancels any running jobs when the sample is exited.
            Task { await model.cancelJob() }
        }
    }
}

/// An asynchronous action associated with the sample.
private enum AsyncAction: Equatable {
    /// Sets up the map for the sample.
    case setUpMap
    /// Generates a geodatabase from the current area of interest.
    case generateGeodatabase
    /// Identifies and selects a feature identified at a given screen point.
    case selectFeature(screenPoint: CGPoint)
    /// Moves the selected feature to a given map point.
    case moveSelectedFeature(mapPoint: Point)
    /// Synchronizes the geodatabase and the feature service.
    case sync
    /// Cancels the current job.
    case cancelJob
    /// Resets the sample.
    case reset

    /// The message to display when the action successfully completes.
    var completionMessage: String {
        switch self {
        case .setUpMap: "Tap the generate button to take the area offline."
        case .generateGeodatabase: "Tap on a feature to edit."
        case .selectFeature: "Tap on the map to move the feature."
        case .moveSelectedFeature: "Tap the sync button to sync the edits."
        case .sync: "Geodatabase sync successful."
        case .cancelJob: "Job canceled."
        default: "Unknown"
        }
    }
}

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