Generate offline map

View on GitHub
Sample viewer app

Take a web map offline.

Image of generate offline map

Use case

Taking a web map offline allows users continued productivity when their network connectivity is poor or nonexistent. For example, by taking a map offline, a field worker inspecting utility lines in remote areas could still access a feature's location and attribute information.

How to use the sample

When the map loads, zoom to the extent you want to take offline. The red border shows the extent that will be downloaded. Tap the "Generate offline map" button to start the offline map job. The progress view will show the job's progress. When complete, the offline map will replace the online map in the map view.

How it works

  1. Create an AGSMap with an AGSPortalItem pointing to the web map.
  2. Create AGSGenerateOfflineMapParameters with AGSOfflineMapTask.defaultGenerateOfflineMapParameters(withAreaOfInterest:completion:) specifying the download area geometry.
  3. Create an AGSOfflineMapTask with the map.
  4. Create the AGSGenerateOfflineMapJob with AGSOfflineMapTask.generateOfflineMapJob(with:downloadDirectory:) and start it with AGSGenerateOfflineMapJob.start(statusHandler:completion:).
  5. When the job is done, get the offline map within the completion closure.

Relevant API

  • AGSGenerateOfflineMapJob
  • AGSGenerateOfflineMapParameters
  • AGSGenerateOfflineMapResult
  • AGSOfflineMapTask
  • AGSPortal
  • AGSPortalItem

About the data

The map used in this sample shows the Naperville water network within Naperville, IL, USA, with cartography designed for web and mobile devices with offline support.

Additional information

The creation of the offline map can be fine-tuned using "Generate offline map (overrides)" sample, or by using "Generate offline map with local basemap" sample to achieve more customized results.

Tags

download, offline, save, web map

Sample Code

GenerateOfflineMapViewController.swift
                                                                                                                                                                                                                                                 
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
//
// 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 GenerateOfflineMapViewController: UIViewController {
    @IBOutlet var mapView: AGSMapView!
    @IBOutlet var extentView: UIView!
    @IBOutlet var barButtonItem: UIBarButtonItem!
    @IBOutlet var progressView: UIProgressView!
    @IBOutlet var progressLabel: UILabel!
    @IBOutlet var progressParentView: UIView!
    @IBOutlet var cancelButton: UIButton!

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

    private var jobProgressObservation: NSKeyValueObservation?

    override func viewDidLoad() {
        super.viewDidLoad()

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

        addMap()
    }

    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

        // disable the bar button item until the map loads
        mapView.map?.load { [weak self] (error) in
            guard let self = self else {
                return
            }

            if let error = error {
                if (error as NSError).code != NSUserCancelledError {
                    // show error
                    self.presentAlert(error: error)
                }
                return
            }

            self.barButtonItem.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 else {
            return
        }

        let downloadDirectory = getNewOfflineMapDirectoryURL()

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

        // observe the job's progress
        jobProgressObservation = generateOfflineMapJob.progress.observe(\.fractionCompleted, options: .new) { [weak self] (progress, _) in
            DispatchQueue.main.async {
                // 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 KVO observer
            self.jobProgressObservation = 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
    }

    // MARK: - Actions

    @IBAction func generateOfflineMapAction() {
        // disable bar button item
        barButtonItem.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 parameters = parameters,
                let self = self else {
                return
            }

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

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

            // take map offline
            self.takeMapOffline()
        }
    }

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

        progressParentView.isHidden = true
        progressView.progress = 0
        progressLabel.text = ""

        // enable take map offline bar button item
        barButtonItem.isEnabled = true

        // unhide the extent view
        extentView.isHidden = false
    }

    // MARK: - Helper methods

    private func showLoginQueryAlert() {
        let alertController = UIAlertController(title: nil, message: "This sample requires you to login in order to take the map's basemap offline. Would you like to continue?", preferredStyle: .alert)
        let loginAction = UIAlertAction(title: "Login", style: .default) { [weak self] (_) in
            self?.addMap()
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)

        alertController.addAction(cancelAction)
        alertController.addAction(loginAction)
        alertController.preferredAction = loginAction
        present(alertController, animated: true)
    }

    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 getNewOfflineMapDirectoryURL() -> URL {
        // get a suitable directory to place files
        let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

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

        return documentDirectoryURL.appendingPathComponent("\(formattedDate)")
    }
}

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