Generate offline map (overrides)

View on GitHubSample viewer app

Take a web map offline with additional options for each layer.

Image of generate offline map overrides

Use case

When taking a web map offline, you may adjust the data (such as layers or tiles) that is downloaded by using custom parameter overrides. This can be used to reduce the extent of the map or the download size of the offline map. It can also be used to highlight specific data by removing irrelevant data. Additionally, this workflow allows you to take features offline that don't have a geometry - for example, features whose attributes have been populated in the office, but still need a site survey for their geometry.

How to use the sample

Modify the overrides parameters:

  • Use the sliders to adjust the the minimum and maximum scale levels and buffer radius to be taken offline for the streets basemap.
  • Toggle the switches for the feature operational layers you want to include in the offline map.
  • Use the min hydrant flow rate slider to only download features with a flow rate higher than this value.
  • Turn on the "Water Pipes" switch if you want to crop the water pipe features to the extent of the map.

After you have set up the overrides to your liking, tap "Start" to start the download. A progress bar will display. Tap "Cancel" if you want to stop the download. When the download is complete, the view will display the offline map. Pan around to see that it is cropped to the download area's extent.

How it works

  1. Load a web map from an AGSPortalItem. Authenticate with the portal if required.
  2. Create an AGSOfflineMapTask with the map.
  3. Generate default task parameters using the extent area you want to download with the AGSOfflineMapTask.defaultGenerateOfflineMapParameters(withAreaOfInterest:completion:) method.
  4. Generate additional "override" parameters using the default parameters with the AGSOfflineMapTask.generateOfflineMapParameterOverrides(with:completion:) method.
  5. For the basemap:
    • Get the parameters AGSOfflineMapParametersKey for the basemap layer.
    • Get the AGSExportTileCacheParameters for the basemap layer from AGSGenerateOfflineMapParameterOverrides exportTileCacheParameters[key] with the key above.
    • Set the level IDs you want to download by setting the levelIDs property of AGSExportTileCacheParameters.
    • To buffer the extent, set a buffered geometry to the areaOfInterest property of AGSExportTileCacheParameters, where the buffered geometry can be calculated with the AGSGeometryEngine.
  6. To remove operational layers from the download:
    • Create an AGSOfflineMapParametersKey with the operational layer.
    • Use the key to obtain the relevant AGSGenerateGeodatabaseParameters from the generateGeodatabaseParameters property of AGSGenerateOfflineMapParameterOverrides.
    • Loop through each AGSGenerateLayerOption and remove it from the geodatabase parameters' layerOptions if the layer option's ID matches the serviceLayerID.
  7. To filter the features downloaded in an operational layer:
    • Get the layer options for the operational layer using the directions in step 6.
    • Loop through the layer options. If the option layerID matches the layer's ID, set the filter's whereClause property.
  8. To not crop a layer's features to the extent of the offline map (default is true):
    • Set useGeometry property of AGSGenerateLayerOption to false.
  9. Create an AGSGenerateOfflineMapJob with AGSOfflineMapTask.generateOfflineMapJob(with:parameterOverrides:downloadDirectory:). Start the job with AGSGenerateOfflineMapJob.start(statusHandler:completion:).
  10. When the job is done, get a reference to the offline map with AGSGenerateOfflineMapResult.offlineMap.

Relevant API

  • AGSExportTileCacheParameters
  • AGSGenerateGeodatabaseParameters
  • AGSGenerateLayerOption
  • AGSGenerateOfflineMapJob
  • AGSGenerateOfflineMapParameterOverrides
  • AGSGenerateOfflineMapParameters
  • AGSGenerateOfflineMapResult
  • AGSOfflineMapParametersKey
  • AGSOfflineMapTask

Additional information

For applications where you just need to take all layers offline, use the standard workflow (using only AGSGenerateOfflineMapParameters). For a simple example of how you take a map offline, please consult the "Generate offline map" sample.

Tags

adjust, download, extent, filter, LOD, offline, override, parameters, reduce, scale range, setting

Sample Code

GenerateOfflineMapOverridesViewController.swiftGenerateOfflineMapOverridesViewController.swiftOfflineMapParameterOverridesViewController.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//
// Copyright 2018 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 GenerateOfflineMapOverridesViewController: UIViewController {
    @IBOutlet weak var mapView: AGSMapView!
    @IBOutlet weak var extentView: UIView!
    @IBOutlet weak var generateButtonItem: UIBarButtonItem!
    @IBOutlet weak var progressView: UIProgressView!
    @IBOutlet weak var progressLabel: UILabel!
    @IBOutlet weak var progressParentView: UIView!
    @IBOutlet weak var cancelButton: UIButton!

    private var portalItem: AGSPortalItem?
    private var parameters: AGSGenerateOfflineMapParameters?
    private var parameterOverrides: AGSGenerateOfflineMapParameterOverrides?
    private var offlineMapTask: AGSOfflineMapTask?
    private var generateOfflineMapJob: AGSGenerateOfflineMapJob?

    private var progressObservation: NSKeyValueObservation?

    override func viewDidLoad() {
        super.viewDidLoad()

        // add the source code button item to the right of navigation bar
        (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["GenerateOfflineMapOverridesViewController", "OfflineMapParameterOverridesViewController"]

        addMap()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // remove key-value observation
        progressObservation = nil
    }

    private func addMap() {
        // portal for the web map
        let portal = AGSPortal.arcGISOnline(withLoginRequired: false)

        // portal item for web map
        let portalItem = AGSPortalItem(portal: portal, itemID: "acc027394bc84c2fb04d1ed317aac674")
        self.portalItem = portalItem

        // map from portal item
        let map = AGSMap(item: portalItem)

        // assign map to the map view
        mapView.map = map

        // load the map
        mapView.map?.load { [weak self] (error) in
            guard let self = self else {
                return
            }

            if let error = error {
                // don't show an error if the user cancelled from the login screen
                if (error as NSError).code != NSUserCancelledError {
                    // show error
                    self.presentAlert(error: error)
                }
                return
            }

            self.generateButtonItem.isEnabled = true
        }

        // instantiate offline map task
        offlineMapTask = AGSOfflineMapTask(portalItem: portalItem)

        // setup extent view
        extentView.layer.borderColor = UIColor.red.cgColor
        extentView.layer.borderWidth = 3
    }

    private func takeMapOffline() {
        guard let offlineMapTask = offlineMapTask,
            let parameters = parameters,
            let parameterOverrides = parameterOverrides else {
            return
        }

        let downloadDirectory = getNewOfflineGeodatabaseURL()

        let generateOfflineMapJob = offlineMapTask.generateOfflineMapJob(with: parameters,
                                                                         parameterOverrides: parameterOverrides,
                                                                         downloadDirectory: downloadDirectory)
        self.generateOfflineMapJob = generateOfflineMapJob

        progressObservation = generateOfflineMapJob.progress.observe(\.fractionCompleted, options: .initial) { [weak self] (progress, _) in
            DispatchQueue.main.async {
                guard let self = self else {
                    return
                }

                // update progress label
                self.progressLabel.text = progress.localizedDescription

                // update progress view
                self.progressView.progress = Float(progress.fractionCompleted)
            }
        }

        // unhide the progress parent view
        progressParentView.isHidden = false

        // start the job
        generateOfflineMapJob.start(statusHandler: nil) { [weak self] (result, error) in
            guard let self = self else {
                return
            }

            // remove key-value observation
            self.progressObservation = nil

            if let error = error {
                // do not display error if user simply cancelled the request
                if (error as NSError).code != NSUserCancelledError {
                    self.presentAlert(error: error)
                }
            } else if let result = result {
                self.offlineMapGenerationDidSucceed(with: result)
            }
        }
    }

    /// Called when the generate offline map job finishes successfully.
    ///
    /// - Parameter result: The result of the generate offline map job.
    func offlineMapGenerationDidSucceed(with result: AGSGenerateOfflineMapResult) {
        // Show any layer or table errors to the user.
        if let layerErrors = result.layerErrors as? [AGSLayer: Error],
            let tableErrors = result.tableErrors as? [AGSFeatureTable: Error],
            !(layerErrors.isEmpty && tableErrors.isEmpty) {
            let errorMessages = layerErrors.map { "\($0.key.name): \($0.value.localizedDescription)" } +
                tableErrors.map { "\($0.key.displayName): \($0.value.localizedDescription)" }
            presentAlert(title: "Offline Map Generated with Errors",
                         message: "The following error(s) occurred while generating the offline map:\n\n\(errorMessages.joined(separator: "\n"))")
        }

        // disable cancel button
        cancelButton.isEnabled = false

        // assign offline map to map view
        mapView.map = result.offlineMap
    }

    func openParameterOverridesViewController() {
        // instantiate the view controller
        let paramNavigationController = storyboard!.instantiateViewController(withIdentifier: "OfflineParametersNavigationController") as! UINavigationController
        let paramController = paramNavigationController.viewControllers.first as! OfflineMapParameterOverridesViewController
        paramController.parameterOverrides = parameterOverrides
        paramController.map = mapView.map

        // set the completion handler
        paramController.startJobHandler = { [weak self] (paramController) in
            // start the job
            self?.takeMapOffline()
            // close the view
            paramController.navigationController?.dismiss(animated: true)
        }
        paramController.cancelHandler = { [weak self] (paramController) in
            // reset the UI
            self?.resetUIForOfflineMapGeneration()
            // close the view
            paramController.navigationController?.dismiss(animated: true)
        }
        // display the parameters sheet
        present(paramNavigationController, animated: true)
    }

    func resetUIForOfflineMapGeneration() {
        // close and reset the progress view
        progressParentView.isHidden = true
        progressView.progress = 0
        progressLabel.text = ""

        // enable take map offline bar button item
        generateButtonItem.isEnabled = true
        // unhide the extent view
        extentView.isHidden = false
    }

    // MARK: - Actions

    @IBAction func generateOfflineMapAction() {
        guard let offlineMapTask = offlineMapTask else {
            return
        }

        // disable bar button item
        generateButtonItem.isEnabled = false
        // hide the extent view
        extentView.isHidden = true

        // show progress hud
        UIApplication.shared.showProgressHUD(message: "Getting default parameters")

        // get the area outlined by the extent view
        let areaOfInterest = extentViewFrameToEnvelope()

        // default parameters for offline map task
        offlineMapTask.defaultGenerateOfflineMapParameters(withAreaOfInterest: areaOfInterest) { [weak self] (parameters: AGSGenerateOfflineMapParameters?, error: Error?) in
            // dismiss progress hud
            UIApplication.shared.hideProgressHUD()

            guard let self = self else {
                return
            }

            if let error = error {
                self.presentAlert(error: error)
                return
            }

            guard let parameters = parameters else {
                return
            }

            // will need the parameters for creating the job later
            self.parameters = parameters

            // build the parameter overrides object to be configured by the user
            offlineMapTask.generateOfflineMapParameterOverrides(with: parameters) { [weak self] (parameterOverrides, error) in
                guard let self = self else {
                    return
                }

                if let error = error {
                    self.presentAlert(error: error)
                    return
                }

                guard let parameterOverrides = parameterOverrides else {
                    return
                }
                self.parameterOverrides = parameterOverrides

                // now that we have the override object, show the overrides UI
                self.openParameterOverridesViewController()
            }
        }
    }

    @IBAction func cancelAction() {
        // cancel generate offline map job
        generateOfflineMapJob?.progress.cancel()

        resetUIForOfflineMapGeneration()
    }

    // MARK: - Helper methods

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

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

        // 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 getNewOfflineGeodatabaseURL() -> URL {
        // get a suitable directory to place files
        let directoryURL = FileManager.default.temporaryDirectory

        // create a unique name for the geodatabase based on current timestamp
        let formattedDate = ISO8601DateFormatter().string(from: Date())

        return directoryURL.appendingPathComponent("\(formattedDate).geodatabase")
    }
}

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