Add features with contingent values

View on GitHub
Sample viewer app

Create and add features whose attribute values satisfy a predefined set of contingencies.

Add features with contingent values map Select contingent values

Use case

Contingent values are a data design feature that allow you to make values in one field dependent on values in another field. Your choice for a value on one field further constrains the domain values that can be placed on another field. In this way, contingent values enforce data integrity by applying additional constraints to reduce the number of valid field inputs.

For example, a field crew working in a sensitive habitat area may be required to stay a certain distance away from occupied bird nests, but the size of that exclusion area differs depending on the bird's level of protection according to presiding laws. Surveyors can add points of bird nests in the work area and their selection of the size of the exclusion area will be contingent on the values in other attribute fields.

How to use the sample

Tap on the map to add a feature symbolizing a bird's nest. Then choose values describing the nest's status, protection, and buffer size. Notice how different values are available depending on the values of preceding fields. Once the contingent values are validated, tap "Done" to add the feature to the map.

How it works

  1. Create and load the AGSGeodatabase from the mobile geodatabase location on file.
  2. Load the first AGSGeodatabaseFeatureTable.
  3. Load the AGSContingentValuesDefinition from the feature table.
  4. Create a new AGSFeatureLayer from the feature table and add it to the map.
  5. Create a new AGSFeature using AGSFeatureTable.createFeature()
  6. Get the first field by name using AGSFeatureTable.field(forName:).
  7. Then get the field's domain as an AGSCodedValueDomain.
  8. Get the coded value domain's codedValues to get an array of AGSCodedValues.
  9. After selecting a value from the initial coded values for the first field, retrieve the remaining valid contingent values for each field as you select the values for the attributes.
    i. Get the AGSContingentValueResults by using contingentValues(with:field:) with the feature and the target field by name.
    ii. Get an array of valid AGSContingentValues from AGSContingentValuesResult.contingentValuesByFieldGroup dictionary with the name of the relevant field group.
    iii. Iterate through the array of valid contingent values to create an array of AGSContingentCodedValue names or the minimum and maximum values of a AGSContingentRangeValue depending on the type of AGSContingentValue returned.
  10. Validate the feature's contingent values by using validateContingencyConstraints(with:) with the current feature. If the resulting array is empty, the selected values are valid.

Relevant API

  • AGSArcGISFeatureTable
  • AGSCodedValue
  • AGSCodedValueDomain
  • AGSContingencyConstraintViolation
  • AGSContingentCodedValue
  • AGSContingentRangeValue
  • AGSContingentValuesDefinition
  • AGSContingentValuesResult

Offline data

This sample uses the Contingent values birds nests mobile geodatabase and the Fillmore topographic map vector tile package for the basemap.

About the data

The mobile geodatabase contains birds nests in the Fillmore area, defined with contingent values. Each feature contains information about its status, protection, and buffer size.

Additional information

Learn more about contingent values and how to utilize them on the ArcGIS Pro documentation.

Tags

coded values, contingent values, feature table, geodatabase

Sample Code

AddFeaturesContingentValuesViewController.swiftAddFeaturesContingentValuesViewController.swiftContingentValuesViewController.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
// Copyright 2022 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 AddFeaturesContingentValuesViewController: UIViewController {
    @IBOutlet var mapView: AGSMapView! {
        didSet {
            mapView.map = makeMap()
            // Add the graphics overlay to the map view.
            mapView.graphicsOverlays.add(graphicsOverlay)
            // Set the map view's touch delegate.
            mapView.touchDelegate = self
        }
    }

    let geodatabase: AGSGeodatabase!
    /// The graphics overlay to add the feature to.
    let graphicsOverlay = AGSGraphicsOverlay()
    /// The geodatabase's feature table.
    var featureTable: AGSArcGISFeatureTable?
    /// The map point to add the feature to.
    var mapPoint: AGSPoint?
    /// The vector tiled layer to use as a basemap.
    var fillmoreVectorTiledLayer: AGSArcGISVectorTiledLayer?

    required init?(coder: NSCoder) {
        let geodatabaseURL = Bundle.main.url(forResource: "ContingentValuesBirdNests", withExtension: "geodatabase")!
        do {
            // Create a temporary directory.
            let temporaryDirectoryURL = try FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: geodatabaseURL, create: true)
            // Create a temporary URL where the geodatabase URL can be copied to.
            let temporaryGeodatabaseURL = temporaryDirectoryURL.appendingPathComponent("birdsNestGDB", isDirectory: false).appendingPathExtension("geodatabase")
            // Copy the item to the temporary URL.
            try FileManager.default.copyItem(at: geodatabaseURL, to: temporaryGeodatabaseURL)
            // Create the geodatabase with the URL.
            geodatabase = AGSGeodatabase(fileURL: temporaryGeodatabaseURL)
        } catch {
            print("Error setting up geodatabase: \(error)")
            geodatabase = nil
        }

        super.init(coder: coder)

        // Load the geodatabase.
        geodatabase?.load { [weak self] (error) in
            let result: Result<Void, Error>
            if let error = error {
                result = .failure(error)
            } else {
                result = .success(())
            }
            self?.geodatabaseDidLoad(with: result)
        }
    }

    deinit {
        if let geodatabase = geodatabase {
            geodatabase.close()
            // Remove all of the temporary files.
            try? FileManager.default.removeItem(at: geodatabase.fileURL)
            // Remove the temporary directory.
            let temporaryGeodatabaseURL = geodatabase.fileURL.deletingLastPathComponent()
            try? FileManager.default.removeItem(at: temporaryGeodatabaseURL)
        }
    }

    /// Called in response to the geodatabase load operation completing.
    func geodatabaseDidLoad(with result: Result<Void, Error>) {
        switch result {
        case .success:
            // Get and load the first feature table in the geodatabase.
            let featureTable = geodatabase.geodatabaseFeatureTables[0]
            self.featureTable = featureTable
            featureTable.load { [weak self] error in
                guard let self = self else { return }
                if let error = error {
                    self.presentAlert(error: error)
                } else {
                    // Create and load the feature layer from the feature table.
                    let featureLayer = AGSFeatureLayer(featureTable: featureTable)
                    // Add the feature layer to the map.
                    self.mapView.map?.operationalLayers.add(featureLayer)
                    // Set the map's viewpoint to the feature layer's full extent.
                    let extent = featureLayer.fullExtent
                    self.mapView.setViewpoint(AGSViewpoint(targetExtent: extent!))
                    // Add buffer graphics for the feature layer.
                    self.queryFeatures()
                }
            }
        case .failure(let error):
            presentAlert(error: error)
        }
    }

    /// Create a map with a vector tiled layer basemap.
    func makeMap() -> AGSMap {
        // Get the vector tiled layer by name.
        let fillmoreVectorTiledLayer = AGSArcGISVectorTiledLayer(name: "FillmoreTopographicMap")
        self.fillmoreVectorTiledLayer = fillmoreVectorTiledLayer
        // Use the vector tiled layer as a basemap.
        let basemap = AGSBasemap(baseLayer: fillmoreVectorTiledLayer)
        let map = AGSMap(basemap: basemap)
        return map
    }

    /// Create buffer graphics for the features.
    func queryFeatures() {
        guard let featureTable = featureTable else { return }
        // Create the query parameters.
        let queryParameters = AGSQueryParameters()
        // Set the where clause to filter for buffer sizes greater than 0.
        queryParameters.whereClause = "BufferSize > 0"
        // Query the features with the query parameters.
        featureTable.queryFeatures(with: queryParameters) { [weak self] result, error in
            guard let self = self else { return }
            if let error = error {
                // Present an alert if there is an error while querying the features.
                self.presentAlert(error: error)
            } else if let result = result {
                // Creates buffer symbol for each feature according to its buffer size.
                let newGraphics = result.featureEnumerator().allObjects.map(self.makeGraphic(feature:))
                // Replace existing graphics with the new graphics.
                self.graphicsOverlay.graphics.setArray(newGraphics)
            }
        }
    }

    /// Add a single feature to the map.
    func addFeature(at mapPoint: AGSPoint) {
        // Create a symbol to represent a bird's nest.
        let symbol = AGSSimpleMarkerSymbol(style: .circle, color: .black, size: 11)
        // Add the graphic to the graphics overlay.
        graphicsOverlay.graphics.add(AGSGraphic(geometry: mapPoint, symbol: symbol))
        // Show the attributes table view.
        performSegue(withIdentifier: "AddFeature", sender: self)
    }

    /// Create a graphic for the given feature.
    func makeGraphic(feature: AGSFeature) -> AGSGraphic {
        // Get the feature's buffer size.
        let bufferSize = feature.attributes["BufferSize"] as! Double
        // Get a polygon using the feature's buffer size and geometry.
        let polygon = AGSGeometryEngine.bufferGeometry(feature.geometry!, byDistance: bufferSize)
        // Create the outline for the buffers.
        let lineSymbol = AGSSimpleLineSymbol(style: .solid, color: .black, width: 2)
        // Create the buffer symbol.
        let bufferSymbol = AGSSimpleFillSymbol(style: .forwardDiagonal, color: .red, outline: lineSymbol)
        // Create an a graphic and add it to the array.
        return AGSGraphic(geometry: polygon, symbol: bufferSymbol)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Add the source code button item to the right of navigation bar.
        (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = [
            "AddFeaturesContingentValuesViewController",
            "ContingentValuesViewController"
        ]
    }

    // MARK: Navigation

    /// Prepare for the segue.
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Set the controller and its properties.
        if let navigationController = segue.destination as? UINavigationController,
           let controller = navigationController.viewControllers.first as? ContingentValuesViewController {
            controller.isModalInPresentation = true
            controller.featureTable = featureTable
            controller.delegate = self
        }
    }
}

extension AddFeaturesContingentValuesViewController: ContingentValuesViewControllerDelegate {
    func contingentValuesViewController(_ controller: ContingentValuesViewController, didCreate feature: AGSFeature) {
        feature.geometry = mapPoint
        // Add the feature to the feature table.
        featureTable?.add(feature) { [weak self] _ in
            guard let self = self else { return }
            let graphic = self.makeGraphic(feature: feature)
            // Add the graphic to the graphics overlay.
            self.graphicsOverlay.graphics.add(graphic)
        }
    }

    func contingentValuesViewControllerDidCancel(_ controller: ContingentValuesViewController) {
        // Remove the last graphic added.
        graphicsOverlay.graphics.removeLastObject()
    }
}

// MARK: - AGSGeoViewTouchDelegate

extension AddFeaturesContingentValuesViewController: AGSGeoViewTouchDelegate {
    func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
        guard let mapExtent = fillmoreVectorTiledLayer?.fullExtent else { return }
        // Ensure that the map point is within the extent.
        if AGSGeometryEngine.geometry(mapPoint, within: mapExtent) {
            // Get the point on the map where the user tapped.
            self.mapPoint = mapPoint
            addFeature(at: mapPoint)
        } else {
            presentAlert(title: nil, message: "Please select a point within the layer's extent.")
        }
    }
}

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