Edit and sync features

View on GitHubSample viewer app

Synchronize offline edits with a feature service.

Edit and sync features

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 to be taken offline. Tap "Generate geodatabase" to take the area offline. To edit features, tap to select a feature, 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 an AGSGeodatabaseSyncTask from a URL to a feature service.
  2. Generate the geodatabase sync task with default parameters using AGSGeodatabaseSyncTask.defaultGenerateGeodatabaseParameters(withExtent:completion:).
  3. Create an AGSGenerateGeodatabaseJob object using AGSGeodatabaseSyncTask.generateJob(with:downloadFileURL:), passing in the parameters and a path to where the geodatabase should be downloaded locally.
  4. Start the job and get a geodatabase as a result.
  5. Set the sync direction to .bidirectional.
  6. 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.
  7. Create an AGSSyncGeodatabaseJob object using AGSGeodatabaseSyncTask.syncJob(with:geodatabase:), passing in the parameters and geodatabase as arguments.
  8. Start the sync job to synchronize the edits.

Relevant API

  • AGSFeatureLayer
  • AGSFeatureTable
  • AGSGenerateGeodatabaseJob
  • AGSGenerateGeodatabaseParameters
  • AGSGeodatabaseSyncTask
  • AGSSyncGeodatabaseJob
  • AGSSyncGeodatabaseParameters
  • AGSSyncLayerOption

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

EditAndSyncFeaturesViewController.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//
// Copyright © 2019 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
//
//   http://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 UIKit
import ArcGIS

class EditAndSyncFeaturesViewController: UIViewController {
    @IBOutlet var mapView: AGSMapView! {
        didSet {
            // Initialize map with a basemap.
            let tileCache = AGSTileCache(name: "SanFrancisco")
            let tiledLayer = AGSArcGISTiledLayer(tileCache: tileCache)
            let map = AGSMap(basemap: AGSBasemap(baseLayer: tiledLayer))
            // Assign the map to the map view.
            mapView.map = map
        }
    }

    @IBOutlet var extentView: UIView! {
        didSet {
            // Set up extent view.
            extentView.layer.borderColor = UIColor.red.cgColor
            extentView.layer.borderWidth = 3
        }
    }

    @IBOutlet private var barButtonItem: UIBarButtonItem!
    @IBOutlet private var instructionsLabel: UILabel!

    private let featureServiceURL = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer")!
    private let syncGeodatabaseTitle = "Sync geodatabase"
    private var generateJob: AGSGenerateGeodatabaseJob?
    private var syncJob: AGSSyncGeodatabaseJob?
    private var geodatabaseSyncTask: AGSGeodatabaseSyncTask!
    private var geodatabase: AGSGeodatabase!
    private var areaOfInterest: AGSEnvelope!

    private var selectedFeature: AGSFeature? {
        didSet {
            if let feature = selectedFeature,
               let featureLayer = feature.featureTable?.layer as? AGSFeatureLayer {
                featureLayer.select(feature)
            } else {
                clearSelection()
            }
        }
    }

    private func extentViewFrameToEnvelope() -> AGSEnvelope {
        let frame = mapView.convert(extentView.frame, from: view)

        // Set the lower-left coner.
        let minPoint = mapView.screen(toLocation: frame.origin)

        // Set the upper-right corner.
        let maxPoint = mapView.screen(toLocation: CGPoint(x: frame.maxX, y: frame.maxY))

        // Return the envenlope covering the entire extent frame.
        return AGSEnvelope(min: minPoint, max: maxPoint)
    }

    private func addFeatureLayers() {
        // Iterate through the layers in the service.
        geodatabaseSyncTask?.load { [weak self] (error) in
            guard let self = self else { return }
            if let error = error {
                self.presentAlert(error: error)
            } else {
                let featureServiceInfo = self.geodatabaseSyncTask.featureServiceInfo!
                let featureLayers = featureServiceInfo.layerInfos.compactMap { (layerInfo) -> AGSFeatureLayer? in
                    let layerID = layerInfo.id
                    guard layerID >= 0 else { return nil }
                    let layerURL = self.featureServiceURL.appendingPathComponent(String(layerID))
                    let featureTable = AGSServiceFeatureTable(url: layerURL)
                    return AGSFeatureLayer(featureTable: featureTable)
                }
                self.mapView.map?.operationalLayers.addObjects(from: featureLayers)
                self.barButtonItem.isEnabled = true
            }
        }
    }

    // Clears selection in all layers of the map.
    private func clearSelection() {
        if let operationalLayers = mapView.map?.operationalLayers {
            for layer in operationalLayers {
                if let layer = layer as? AGSFeatureLayer {
                    layer.clearSelection()
                }
            }
        }
    }

    private func resetUI() {
        selectedFeature = nil
        barButtonItem.isEnabled = true
        barButtonItem.title = syncGeodatabaseTitle
        instructionsLabel.text = "Tap the sync button"
    }

    func geodatabaseDidLoad() {
        if let error = geodatabase.loadError {
            self.presentAlert(error: error)
        } else {
            // Iterate through the feature tables in the geodatabase and add new layers to the map.
            self.mapView.map?.operationalLayers.removeAllObjects()
            for geodatabaseFeatureTable in self.geodatabase.geodatabaseFeatureTables {
                geodatabaseFeatureTable.load { [weak self, unowned geodatabaseFeatureTable] (error: Error?) in
                    if let error = error {
                        self?.presentAlert(error: error)
                    } else if geodatabaseFeatureTable.geometryType == .point {
                        // Create a new feature layer from the table and add it to the map.
                        let featureLayer = AGSFeatureLayer(featureTable: geodatabaseFeatureTable)
                        self?.mapView.map?.operationalLayers.add(featureLayer)
                    }
                }
            }
            self.generateJob = nil
            self.barButtonItem.isEnabled = false
            self.instructionsLabel.text = "Tap on a feature"
            self.mapView.touchDelegate = self
            self.mapView.interactionOptions.isPanEnabled = false
            self.mapView.interactionOptions.isZoomEnabled = false
            self.mapView.interactionOptions.isRotateEnabled = false
        }
    }

    func geodatabaseDidSync() {
        self.presentAlert(title: "Geodatabase sync sucessful")
        self.barButtonItem.isEnabled = false
        self.instructionsLabel.text = "Tap on a feature"
    }

    func generateGeodatabase() {
        // Hide the unnecessary items.
        barButtonItem.isEnabled = false

        // Get the area outlined by the extent view.
        areaOfInterest = self.extentViewFrameToEnvelope()

        geodatabaseSyncTask.defaultGenerateGeodatabaseParameters(withExtent: areaOfInterest) { [weak self] (params: AGSGenerateGeodatabaseParameters?, error: Error?) in
            guard let self = self else { return }

            guard let params = params else {
                self.presentAlert(title: "Could not generate default parameters: \(error!)")
                return
            }
            // Don't include attachments to minimize the geodatabase size.
            params.returnAttachments = false

            // Create a temporary file for the geodatabase.
            let dateFormatter = ISO8601DateFormatter()

            let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            let downloadFileURL = documentDirectoryURL
                .appendingPathComponent(dateFormatter.string(from: Date()))
                .appendingPathExtension("geodatabase")

            // Request a job to generate the geodatabase.
            let generateGeodatabaseJob = self.geodatabaseSyncTask.generateJob(with: params, downloadFileURL: downloadFileURL)
            self.generateJob = generateGeodatabaseJob
            generateGeodatabaseJob.start(
                statusHandler: { (status: AGSJobStatus) in
                    UIApplication.shared.showProgressHUD(message: status.statusString()) // Show job status.
                },
                completion: { [weak self] (_, error: Error?) in
                    UIApplication.shared.hideProgressHUD()
                    if let error = error {
                        self?.presentAlert(error: error)
                    } else {
                        // Load the geodatabase when the job is done.
                        self?.geodatabase = generateGeodatabaseJob.result
                        self?.geodatabase.load { [weak self] (_: Error?) in
                            self?.geodatabaseDidLoad()
                        }
                    }
                }
            )
        }
    }

    func syncGeodatabase() {
        barButtonItem.isEnabled = false
        selectedFeature = nil

        // Create parameters for the sync task.
        let syncGeodatabaseParameters = AGSSyncGeodatabaseParameters()
        syncGeodatabaseParameters.geodatabaseSyncDirection = .bidirectional
        syncGeodatabaseParameters.rollbackOnFailure = false

        // Specify the layer IDs of the feature tables to sync.
        for geodatabaseFeatureTable in geodatabase.geodatabaseFeatureTables {
            let serviceLayerId = geodatabaseFeatureTable.serviceLayerID
            let syncLayerOption = AGSSyncLayerOption(layerID: serviceLayerId, syncDirection: .bidirectional)
            syncGeodatabaseParameters.layerOptions.append(syncLayerOption)
        }

        // Create a sync job with the parameters and start it.
        let syncGeodatabaseJob = geodatabaseSyncTask.syncJob(with: syncGeodatabaseParameters, geodatabase: geodatabase)
        self.syncJob = syncGeodatabaseJob
        syncGeodatabaseJob.start(statusHandler: { (status: AGSJobStatus) in
            UIApplication.shared.showProgressHUD(message: status.statusString())
        }, completion: { [weak self] (_: [AGSSyncLayerResult]?, error: Error?) in
            UIApplication.shared.hideProgressHUD()
            if let error = error {
                self?.presentAlert(error: error)
            } else {
                self?.geodatabaseDidSync()
            }
        })
    }

    @IBAction func generateOrSync() {
        if barButtonItem.title == syncGeodatabaseTitle {
            syncGeodatabase()
        } else {
            generateGeodatabase()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add the source code button item to the right of navigation bar.
        (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["EditAndSyncFeaturesViewController"]

        // Create a geodatabase sync task using the feature service URL.
        geodatabaseSyncTask = AGSGeodatabaseSyncTask(url: featureServiceURL)
        addFeatureLayers()
    }
}

// Allows the user to interactively select and move features on the map.
extension EditAndSyncFeaturesViewController: AGSGeoViewTouchDelegate {
    func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
        // Move the selected feature to the tapped location and update it in the feature table.
        if let feature = self.selectedFeature {
            let point = mapView.screen(toLocation: screenPoint)
            if AGSGeometryEngine.geometry(point, intersects: areaOfInterest) {
                feature.geometry = point
                feature.featureTable?.update(feature) { [weak self] ( error: Error?) in
                    if let error = error {
                        self?.presentAlert(error: error)
                        self?.selectedFeature = nil
                    } else {
                        self?.resetUI()
                    }
                }
            } else {
                self.presentAlert(title: "Cannot move feature outside downloaded area")
            }
        } else { // Identify which feature was tapped and select it.
            mapView.identifyLayers(atScreenPoint: screenPoint, tolerance: 22.0, returnPopupsOnly: false, maximumResultsPerLayer: 1) { [weak self] (results: [AGSIdentifyLayerResult]?, error: Error?) in
                if let error = error {
                    self?.presentAlert(error: error)
                } else if let feature = results?.first?.geoElements.first as? AGSFeature {
                    self?.instructionsLabel.text = "Tap on the map to move the feature"
                    self?.selectedFeature = feature
                }
            }
        }
    }
}

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