Toggle between feature request modes

View on GitHub
Sample viewer app

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

Toggle between feature request modes

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 by tapping the "Mode" button. 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 1000 features.

How it works

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

Relevant API

  • AGSFeatureLayer
  • AGSFeatureRequestMode
  • AGSServiceFeatureTable
  • AGSServiceFeatureTable.featureRequestMode
  • AGSServiceFeatureTable.populateFromService(with:clearCache:outFields:completion:)

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

ToggleFeatureRequestModesViewController.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
// Copyright 2021 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 ToggleFeatureRequestModesViewController: UIViewController {
    @IBOutlet var mapView: AGSMapView! {
        didSet {
            mapView.map = AGSMap(basemapStyle: .arcGISTopographic)
            mapView.setViewpoint(AGSViewpoint(latitude: 45.5266, longitude: -122.6219, scale: 6000))
        }
    }
    @IBOutlet var modeBarButtonItem: UIBarButtonItem!
    @IBOutlet var populateBarButtonItem: UIBarButtonItem!
    @IBOutlet var statusLabel: UILabel!

    private static let featureServiceURL = URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/rest/services/Trees_of_Portland/FeatureServer/0")!
    private let featureTable = AGSServiceFeatureTable(url: featureServiceURL)

    private enum FeatureRequestMode: CaseIterable {
        case cache, noCache, manualCache

        var title: String {
            switch self {
            case .cache:
                return "Cache"
            case .noCache:
                return "No cache"
            case .manualCache:
                return "Manual cache"
            }
        }

        var mode: AGSFeatureRequestMode {
            switch self {
            case .cache:
                return .onInteractionCache
            case .noCache:
                return .onInteractionNoCache
            case .manualCache:
                return .manualCache
            }
        }
    }

    /// Prompt mode selection.
    @IBAction private func modeButtonTapped(_ button: UIBarButtonItem) {
        // Set up action sheets.
        let alertController = UIAlertController(
            title: "Choose a feature request mode.",
            message: nil,
            preferredStyle: .actionSheet
        )
        // Create an action for each mode.
        FeatureRequestMode.allCases.forEach { mode in
            let action = UIAlertAction(title: mode.title, style: .default) { [self] _ in
                changeFeatureRequestMode(to: mode.mode)
                let message = "\(mode.title) enabled."
                setStatus(message: message)
            }
            alertController.addAction(action)
        }
        // Add a cancel action.
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
        alertController.addAction(cancelAction)
        alertController.popoverPresentationController?.barButtonItem = modeBarButtonItem
        present(alertController, animated: true)
    }

    /// Populate for manual cache mode.
    @IBAction private func populateManualCache(_ button: UIBarButtonItem) {
        // Set query parameters.
        let params = AGSQueryParameters()
        // Query for all tree conditions except "dead" with coded value '4'.
        params.whereClause = "Condition < '4'"
        params.geometry = mapView.visibleArea?.extent
        // Show the progress HUD.
        UIApplication.shared.showProgressHUD(message: "Populating")
        // Populate features based on the query.
        featureTable.populateFromService(with: params, clearCache: true, outFields: ["*"]) { [weak self] (result: AGSFeatureQueryResult?, error: Error?) in
            guard let self = self else { return }
            // Hide progress HUD.
            UIApplication.shared.hideProgressHUD()
            if let error = error {
                self.presentAlert(error: error)
            } else {
                // Display the number of features found.
                let message = "Populated \(result?.featureEnumerator().allObjects.count ?? 0) features."
                self.setStatus(message: message)
            }
        }
    }

    /// Set the appropriate feature request mode.
    private func changeFeatureRequestMode(to mode: AGSFeatureRequestMode) {
        // Enable or disable the populate bar button item when appropriate.
        if mode == .manualCache {
            populateBarButtonItem.isEnabled = true
        } else {
            populateBarButtonItem.isEnabled = false
        }
        let map = mapView.map!
        map.operationalLayers.removeAllObjects()
        // Set the request mode.
        featureTable.featureRequestMode = mode
        let featureLayer = AGSFeatureLayer(featureTable: featureTable)
        // Add the feature layer to the map.
        map.operationalLayers.add(featureLayer)
    }

    /// Set the status.
    private func setStatus(message: String) {
        statusLabel.text = message
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setStatus(message: "Select a feature request mode.")
        // Add the source code button item to the right of navigation bar.
        (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ToggleFeatureRequestModesViewController"]
    }
}

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