Set feature request mode

View on GitHub

Use different feature request modes to populate the map from a service feature table.

Image of set feature request mode

Use case

Feature tables can be initialized with a feature request mode which controls how frequently features are requested and locally cached in response to panning, zooming, selecting, or querying. The feature request mode affects performance and should be chosen based on considerations such as how often the data is expected to change or how often changes in the data should be reflected to the user.

  • OnInteractionCache - fetches features within the current extent when needed (after a pan or zoom action) from the server and caches those features in a table on the client. Queries will be performed locally if the features are present, otherwise they will be requested from the server. This mode minimizes requests to the server and is useful for large batches of features which will change infrequently.
  • OnInteractionNoCache - always fetches features from the server and doesn't cache any features on the client. This mode is best for features that may change often on the server or whose changes need to always be visible.

NOTE: No cache does not guarantee that features won't be cached locally. Feature request mode is a performance concept unrelated to data security.

  • ManualCache - only fetches features when explicitly populated from a query. This mode is best for features that change minimally or when it is not critical for the user to see the latest changes.

How to use the sample

Choose a request mode. Pan and zoom to see how the features update at different scales. If you choose "Manual Cache", tap the "Populate" button to manually get a cache with a subset of features (where "Condition < 4") within the extent.

Note: The service limits requests to 2000 features.

How it works

  1. Create an ServiceFeatureTable with a feature service URL.
  2. Set the featureRequestMode property of the ServiceFeatureTable to the desired mode (Cache, No cache, or Manual cache) before the table is loaded.
    • If using manualCache, populate the features with ServiceFeatureTable.populateFromService(using:clearCache:outFields:).
  3. Create an FeatureLayer with the feature table and add it to a map's operational layers to display it.

Relevant API

  • FeatureLayer
  • FeatureRequestMode
  • ServiceFeatureTable
  • ServiceFeatureTable.featureRequestMode
  • ServiceFeatureTable.populateFromService(using:clearCache:outFields:)

About the data

This sample uses the Trees of Portland service showcasing over 200,000 street trees in Portland, OR. Each tree point models the health of the tree (green - better, red - worse) as well as the diameter of its trunk.

Tags

cache, data, feature, feature request mode, performance

Sample Code

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

    /// The feature table's current feature request mode.
    @State private var selectedFeatureRequestMode: FeatureRequestMode = .onInteractionCache

    /// The text shown in the overlay at the top of the screen.
    @State private var message = ""

    /// A Boolean value indicating whether the feature table is being populated.
    @State private var isPopulating = false

    /// 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)
                    .overlay(alignment: .top) {
                        Text(message)
                            .frame(maxWidth: .infinity, alignment: .center)
                            .padding(8)
                            .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal)
                    }
                    .toolbar {
                        ToolbarItemGroup(placement: .bottomBar) {
                            Button("Populate") {
                                isPopulating = true
                            }
                            .disabled(selectedFeatureRequestMode != .manualCache)
                            .task(id: isPopulating) {
                                // Populate the feature table when the "Populate" button is tapped.
                                guard isPopulating else { return }
                                defer { isPopulating = false }

                                do {
                                    // Get the current extent of the screen.
                                    let viewRect = geometryProxy.frame(in: .local)
                                    let viewExtent = mapViewProxy.envelope(fromViewRect: viewRect)

                                    // Populate the feature table with features contained in extent.
                                    let count = try await model.populateFeatures(within: viewExtent)
                                    message = "Populated \(count) features."
                                } catch {
                                    self.error = error
                                }
                            }

                            Picker("Feature Request Mode", selection: $selectedFeatureRequestMode) {
                                ForEach(FeatureRequestMode.modeCases, id: \.self) { mode in
                                    Text(mode.label)
                                }
                            }
                            .onChange(of: selectedFeatureRequestMode) { newMode in
                                // Update the feature table's feature request mode.
                                model.featureTable.featureRequestMode = newMode
                                message = "\(model.featureTable.featureRequestMode.label) enabled."
                            }
                        }
                    }
            }
        }
        .overlay(alignment: .center) {
            if isPopulating {
                VStack {
                    Text("Populating")
                    ProgressView()
                        .progressViewStyle(.circular)
                }
                .padding()
                .background(.ultraThickMaterial)
                .cornerRadius(10)
                .shadow(radius: 50)
            }
        }
        .errorAlert(presentingError: $error)
    }
}

private extension SetFeatureRequestModeView {
    /// The view model for the sample.
    class Model: ObservableObject {
        /// A map with a topographic basemap centered on Portland OR, USA.
        let map: Map = {
            let map = Map(basemapStyle: .arcGISTopographic)
            map.initialViewpoint = Viewpoint(latitude: 45.5266, longitude: -122.6219, scale: 6e3)
            return map
        }()

        /// The service feature table.
        let featureTable: ServiceFeatureTable = {
            // Create the table from a URL.
            let featureTable = ServiceFeatureTable(url: .treesOfPortland)

            // Set the initial table's feature request mode.
            featureTable.featureRequestMode = .onInteractionCache

            return featureTable
        }()

        init() {
            // Create a feature layer from the feature table and add it to the map.
            let featureLayer = FeatureLayer(featureTable: featureTable)
            map.addOperationalLayer(featureLayer)
        }

        /// Populates the feature table using queried features contained within a given geometry.
        /// - Parameter geometry: The geometry used to filter the results.
        /// - Returns: The number of features populated.
        func populateFeatures(within geometry: Geometry?) async throws -> Int {
            // Create query parameters to filter for all tree
            // conditions except "dead" (coded value '4').
            let queryParameters = QueryParameters()
            queryParameters.whereClause = "Condition < '4'"
            queryParameters.geometry = geometry

            // Use the query parameters to populate the feature table.
            let featureQueryResult = try await featureTable.populateFromService(
                using: queryParameters,
                clearCache: true,
                outFields: ["*"]
            )

            // Get the amount of features found from the feature query result.
            let featureCount = featureQueryResult.features().reduce(into: Int()) { result, _ in
                result += 1
            }
            return featureCount
        }
    }
}

private extension FeatureRequestMode {
    /// The feature request mode cases that represent a valid mode, e.i., not `undefined`.
    static var modeCases: [Self] {
        return [.onInteractionCache, .onInteractionNoCache, .manualCache]
    }

    /// A human-readable label for the feature request mode.
    var label: String {
        switch self {
        case .undefined:
            return "Undefined"
        case .manualCache:
            return "Manual Cache"
        case .onInteractionCache:
            return "Cache"
        case .onInteractionNoCache:
            return "No Cache"
        @unknown default:
            return "Unknown"
        }
    }
}

private extension URL {
    /// A URL to a feature layer from the "Trees of Portland" feature service.
    static var treesOfPortland: URL {
        URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/rest/services/Trees_of_Portland/FeatureServer/0")!
    }
}

#Preview {
    NavigationView {
        SetFeatureRequestModeView()
    }
}

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