Download preplanned map

View on GitHub
Sample viewer app

Take a map offline using a preplanned map area.

Image of download preplanned map area

Use case

Generating offline maps on demand for a specific area can be time consuming for users and a processing load on the server. If areas of interest are known ahead of time, a web map author can pre-create packages for these areas. This way, the generation only needs to happen once, making the workflow more efficient for users and servers.

An archeology team could define preplanned map areas for dig sites which can be taken offline for field use. To see the difference, compare this sample to the "Generate an offline map" sample.

How to use the sample

Select a preplanned map area by tapping the "Select Map" button and selecting one of the showing available areas. Tapping a cell initiates a download, and shows download progress in the interim. Once downloaded, the preplanned map is displayed in the map view. If a preplanned map is reselected later, the locally cached data is loaded immediately.

How it works

  1. Open the online AGSMap from an AGSPortalItem and display it.
  2. Create an AGSOfflineMapTask using the portal item.
  3. Get the AGSPreplannedMapAreas from the task, and then load them.
  4. To download a selected map area, create the default parameters with AGSOfflineMapTask.defaultDownloadPreplannedOfflineMapParameters(with:completion:) from the task using the selected preplanned map area.
  5. Set the update mode of the preplanned map area.
  6. Call AGSOfflineMapTask.downloadPreplannedOfflineMapJob(with:downloadDirectory:) to find the preplanned areas.
  7. Start the job. Once it has completed, get the AGSDownloadPreplannedOfflineMapResult.
  8. Get the offline AGSMap from the result and display it in the AGSMapView.

Relevant API

  • AGSDownloadPreplannedOfflineMapResult
  • AGSOfflineMapTask
  • AGSOfflineMapTask.defaultDownloadPreplannedOfflineMapParameters(with:completion:)
  • AGSOfflineMapTask.downloadPreplannedOfflineMapJob(with:downloadDirectory:)
  • AGSPreplannedMapArea

About the data

The Naperville stormwater network map is based on ArcGIS Solutions for Stormwater and provides a realistic depiction of a theoretical stormwater network.

Additional information

AGSDownloadPreplannedOfflineMapParameters.updateMode can be used to set the way the preplanned map area receives updates in several ways:

  • noUpdates: No updates will be performed. This mode is intended for when a static snapshot of the data is required, and it does not create a replica. This is the mode used for this sample.
  • syncWithFeatureServices: Changes, including local edits, will be synced directly with the underlying feature services. This is the default update mode.
  • downloadScheduledUpdates: Scheduled, read-only updates will be downloaded from the online map area and applied to the local mobile geodatabases.

For more information about offline workflows, see Offline maps, scenes, and data in the ArcGIS Developers guide.

Tags

map area, offline, pre-planned, preplanned

Sample Code

DownloadPreplannedMapViewController.swiftMapSelectionTableViewController.swiftPreplannedMapAreaTableViewCell.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
//
// Copyright © 2019 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

// MARK: - Constants

private enum Constants {
    static let portalItemIdentifier = "acc027394bc84c2fb04d1ed317aac674"

    static let popoverPreferredWidth: CGFloat = 375
    static let popoverPreferredCompactHeight: CGFloat = 280
    static let popoverPreferredRegularHeight: CGFloat = 360
}

// MARK: - DownloadPreplannedMapViewController

class DownloadPreplannedMapViewController: UIViewController {
    @IBOutlet private weak var mapView: AGSMapView!
    @IBOutlet private weak var activityIndicatorView: UIActivityIndicatorView!
    @IBOutlet private weak var selectMapBarButtonItem: UIBarButtonItem!
    @IBOutlet private weak var removeDownloadsBarButtonItem: UIBarButtonItem!

    private let portal = AGSPortal.arcGISOnline(withLoginRequired: false)
    private var portalItem: AGSPortalItem?
    private var onlineMap: AGSMap?

    private var offlineTask: AGSOfflineMapTask?
    private var cancelable: AGSCancelable?

    private var remoteAvailablePreplannedMapAreas = Set<AGSPreplannedMapArea>()

    private var remoteLoadedPreplannedMapAreas = Set<AGSPreplannedMapArea>() {
        didSet {
            updateView()
        }
    }

    private var uniqueLocalMapPackages = Set<AGSMobileMapPackage>() {
        didSet {
            updateView()
        }
    }

    // MARK: UIViewController

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let navigationController = segue.destination as? UINavigationController,
            let viewController = navigationController.viewControllers.first as? MapSelectionTableViewController {
            navigationController.presentationController?.delegate = self

            let height: CGFloat
            if traitCollection.horizontalSizeClass == .regular, traitCollection.verticalSizeClass == .regular {
                height = Constants.popoverPreferredRegularHeight
            } else {
                height = Constants.popoverPreferredCompactHeight
            }
            let contentSize = CGSize(width: Constants.popoverPreferredWidth, height: height)
            viewController.preferredContentSize = contentSize

            viewController.delegate = self
            viewController.currentlySelectedMap = mapView.map
            viewController.onlineMap = onlineMap
            viewController.availablePreplannedMapAreas = remoteLoadedPreplannedMapAreas.sorted { $0.title < $1.title }
            viewController.localMapPackages = Array(uniqueLocalMapPackages)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let sourceBarButtonItem = navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem else {
            return
        }
        sourceBarButtonItem.filenames = ["DownloadPreplannedMapViewController", "MapSelectionTableViewController", "PreplannedMapAreaTableViewCell"]
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        loadPortal()
    }

    // MARK: IBActions

    @IBAction private func removeDownloadsTapped(_ sender: UIBarButtonItem) {
        guard presentedViewController == nil else { return }

        let alertController = UIAlertController(title: "Delete offline areas?", message: nil, preferredStyle: .actionSheet)

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

        let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { (_) in
            self.removeDownloadedMapPackages()
        }
        alertController.addAction(deleteAction)
        alertController.preferredAction = deleteAction

        alertController.popoverPresentationController?.barButtonItem = sender

        present(alertController, animated: true)
    }

    // MARK: Private behavior

    private func loadOnlineMap() {
        guard let portalItem = portalItem else { return }

        let onlineMap = AGSMap(item: portalItem)
        mapView.map = onlineMap

        activityIndicatorView.startAnimating()

        onlineMap.load { [weak self] (error) in
            guard let self = self else { return }

            self.activityIndicatorView.stopAnimating()

            if let error = error {
                print("Error encountered loading the map : \(error.localizedDescription)")
            } else {
                self.loadPreplannedMapAreas()
            }
        }
        self.onlineMap = onlineMap
    }

    private func loadPortal() {
        guard portal.loadStatus != .loaded else { return }

        let portalItem = AGSPortalItem(portal: portal, itemID: Constants.portalItemIdentifier)
        self.portalItem = portalItem

        activityIndicatorView.startAnimating()

        portal.load { [weak self] (error) in
            guard let self = self else { return }

            self.activityIndicatorView.stopAnimating()

            if let error = error {
                print("Error encountered loading the portal : \(error.localizedDescription)")
            } else {
                self.loadOnlineMap()
                self.retrieveAvailablePreplannedMapAreas()
            }
        }
    }

    private func loadPreplannedMapAreas() {
        activityIndicatorView.startAnimating()

        let remoteAreas = Array(remoteAvailablePreplannedMapAreas)
        AGSLoadObjects(remoteAreas) { [weak self] (success) in
            guard let self = self else { return }

            if !success {
                print("Error encountered loading areas...")
            } else {
                self.activityIndicatorView.stopAnimating()
                self.remoteLoadedPreplannedMapAreas.formUnion(remoteAreas)
            }
        }
    }

    private func removeDownloadedMapPackages() {
        mapView.map = onlineMap

        uniqueLocalMapPackages.forEach { package in
            try? FileManager.default.removeItem(at: package.fileURL)
        }
        uniqueLocalMapPackages.removeAll()
    }

    private func retrieveAvailablePreplannedMapAreas() {
        guard let portalItem = portalItem else { return }

        activityIndicatorView.startAnimating()

        cancelable?.cancel()
        offlineTask = AGSOfflineMapTask(portalItem: portalItem)

        cancelable = offlineTask?.getPreplannedMapAreas { [weak self] (preplannedAreas, error) in
            guard let self = self else { return }

            self.activityIndicatorView.stopAnimating()

            if let error = error {
                print("Error encountered loading preplanned map areas : \(error.localizedDescription)")
            } else if let preplannedAreas = preplannedAreas {
                self.remoteAvailablePreplannedMapAreas.formUnion(preplannedAreas)
                self.loadPreplannedMapAreas()
            }
        }
    }

    private func updateView() {
        selectMapBarButtonItem.isEnabled = !remoteLoadedPreplannedMapAreas.isEmpty
        removeDownloadsBarButtonItem.isEnabled = !uniqueLocalMapPackages.isEmpty
    }
}

// MARK: - MapSelectionDelegate

extension DownloadPreplannedMapViewController: MapSelectionDelegate {
    func didDownloadMapPackageForPreplannedMapArea(_ mapPackage: AGSMobileMapPackage) {
        uniqueLocalMapPackages.insert(mapPackage)
    }

    func didSelectMap(map: AGSMap) {
        mapView.map = map
    }
}

// MARK: - UIAdaptivePresentationControllerDelegate

extension DownloadPreplannedMapViewController: UIAdaptivePresentationControllerDelegate {
    func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return .none    // ensure that the settings are show in a popover even on small displays
    }
}

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