Generate offline map (basemap by reference)

View on GitHubSample viewer app

Take a web map offline, but instead of downloading an online basemap, use one which is already on the device.

Image of generate offline map with local basemap

Use case

There are a number of use-cases where you may wish to use a basemap which is already on the device, rather than downloading:

  • You want to limit the total download size.
  • You want to be able to share a single set of basemap files between many offline maps.
  • You want to use a custom basemap (for example authored in ArcGIS Pro) which is not available online.
  • You do not wish to sign into ArcGIS.com in order to download Esri basemaps.

The author of a web map can support the use of basemaps which are already on a device by configuring the web map to specify the name of a suitable basemap file. This could be a basemap which:

  • Has been authored in ArcGIS Pro to make use of your organizations custom data.
  • Is available as a portal item which can be downloaded once and re-used many times.

How to use the sample

When the sample loads, tap the "Generate Offline Map" button. You will be prompted to choose whether you wish to download the online basemap or use the local "naperville_imagery.tpkx" basemap which is already on the device.

If you choose to download the online basemap, the offline map will be generated with the same (topographic) basemap as the online web map. To download the Esri basemap, you may be prompted to sign in to ArcGIS.com.

If you choose to use the basemap from the device, the offline map will be generated with the local imagery basemap. The download will be quicker since no tiles are exported or downloaded.

Since the application is not exporting online ArcGIS Online basemaps you will not need to log-in.

How it works

  1. Create an AGSPortalItem object using a web map's ID.
  2. Initialize an AGSOfflineMapTask object using the map created with the portal item.
  3. Get the default parameters for the task by calling AGSOfflineMapTask.defaultGenerateOfflineMapParameters(withAreaOfInterest:completion:) with the selected extent.
  4. Check the AGSGenerateOfflineMapParameters.referenceBasemapFilename property. The author of an online web map can configure this setting to indicate the name of a suitable basemap. In this example, the application checks the app bundle for the suggested "naperville_imagery.tpkx" file - and if found, asks the user whether they wish to use this instead of downloading.
  5. Set the AGSGenerateOfflineMapParameters.referenceBasemapDirectory to the absolute path of the directory which contains the .tpkx file, if the user chooses to use the basemap on the device.
  6. Create an AGSGenerateOfflineMapJob by calling AGSOfflineMapTask.generateOfflineMapJob(with:downloadDirectory:) passing the parameters and the download location for the offline map.
  7. Start the AGSGenerateOfflineMapJob. It will check whether AGSGenerateOfflineMapParameters.referenceBasemapDirectory has been set. If this property is set, no online basemap will be downloaded and instead, the mobile map will be created with a reference to the .tpkx on the device.

Relevant API

  • AGSGenerateOfflineMapJob
  • AGSGenerateOfflineMapParameters
  • AGSGenerateOfflineMapResult
  • AGSOfflineMapTask

Offline data

This sample uses naperville_imagery.tpkx TileCache. It is downloaded from ArcGIS Online automatically.

Tags

basemap, download, local, offline, save, web map

Sample Code

GenerateOfflineMapBasemapByReferenceViewController.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
//
// 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

/// A view controller that manages the interface of the Generate Offline Map
/// (Basemap by Reference) sample.
class GenerateOfflineMapBasemapByReferenceViewController: UIViewController {
    /// The map view managed by the view controller.
    @IBOutlet weak var mapView: AGSMapView! {
        didSet {
            mapView.map = makeMap()
            // Set inset of overlay.
            let padding: CGFloat = 30
            mapView.layoutMargins = UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding)
        }
    }
    /// The view used to show the geographic area for which the map data should
    /// be taken offline.
    @IBOutlet weak var areaOfInterestView: UIView!
    /// The button item that starts generating an offline map.
    @IBOutlet weak var generateButtonItem: UIBarButtonItem!

    /// Creates a map.
    ///
    /// - Returns: A new `AGSMap` object.
    func makeMap() -> AGSMap {
        let portal = AGSPortal.arcGISOnline(withLoginRequired: false)
        let portalItem = AGSPortalItem(portal: portal, itemID: "acc027394bc84c2fb04d1ed317aac674")
        let map = AGSMap(item: portalItem)
        map.load { [weak self] _ in self?.mapDidLoad() }
        return map
    }

    /// Called in response to the map load operation completing.
    func mapDidLoad() {
        guard let map = mapView.map else { return }
        if let error = map.loadError {
            presentAlert(error: error)
        } else {
            generateButtonItem.isEnabled = true
        }
    }

    /// Called in response to the Generate Offline Map button item being tapped.
    @IBAction func generateOfflineMap() {
        generateButtonItem.isEnabled = false
        mapView.isUserInteractionEnabled = false
        let offlineMapTask = AGSOfflineMapTask(onlineMap: mapView.map!)
        offlineMapTask.defaultGenerateOfflineMapParameters(withAreaOfInterest: areaOfInterest) { [weak self] (parameters, error) in
            if let parameters = parameters {
                self?.offlineMapTask(offlineMapTask, didCreate: parameters)
            } else if let error = error {
                self?.offlineMapTask(offlineMapTask, didFailToCreateParametersWith: error)
            }
        }
    }

    func offlineMapTask(_ offlineMapTask: AGSOfflineMapTask, didCreate parameters: AGSGenerateOfflineMapParameters) {
        let filename = parameters.referenceBasemapFilename as NSString
        let name = filename.deletingPathExtension
        let `extension` = filename.pathExtension
        if let url = Bundle.main.url(forResource: name, withExtension: `extension`) {
            let message: String = {
                let displayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String
                return String(format: "“%@” has a local version of the basemap used by the map. Would you like to use the local or the online basemap?", displayName)
            }()
            let alertController = UIAlertController(title: "Choose Basemap", message: message, preferredStyle: .actionSheet)
            let offlineAction = UIAlertAction(title: "Local", style: .default) { (_) in
                parameters.referenceBasemapDirectory = url.deletingLastPathComponent()
                self.takeMapOffline(task: offlineMapTask, parameters: parameters)
            }
            alertController.addAction(offlineAction)
            let onlineAction = UIAlertAction(title: "Online", style: .default) { (_) in
                self.takeMapOffline(task: offlineMapTask, parameters: parameters)
            }
            alertController.addAction(onlineAction)
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
                self.generateButtonItem.isEnabled = true
                self.mapView.isUserInteractionEnabled = true
            }
            alertController.addAction(cancelAction)
            alertController.preferredAction = offlineAction
            alertController.popoverPresentationController?.barButtonItem = generateButtonItem
            present(alertController, animated: true)
        } else {
            takeMapOffline(task: offlineMapTask, parameters: parameters)
        }
    }

    func offlineMapTask(_ offlineMapTask: AGSOfflineMapTask, didFailToCreateParametersWith error: Error) {
        presentAlert(error: error)
        generateButtonItem.isEnabled = true
        mapView.isUserInteractionEnabled = true
    }

    /// The geographic area for which the map data should be taken offline.
    var areaOfInterest: AGSEnvelope {
        let frame = mapView.convert(areaOfInterestView.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 AGSEnvelope(min: minPoint, max: maxPoint)
    }

    /// The generate offline map job.
    var generateOfflineMapJob: AGSGenerateOfflineMapJob?
    /// The view that displays the progress of the job.
    var downloadProgressView: DownloadProgressView?

    func takeMapOffline(task offlineMapTask: AGSOfflineMapTask, parameters: AGSGenerateOfflineMapParameters) {
        guard let downloadDirectoryURL = try? FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: Bundle.main.bundleURL, create: true).appendingPathComponent(UUID().uuidString) else {
            assertionFailure("Could not create temporary directory.")
            return
        }
        let job = offlineMapTask.generateOfflineMapJob(with: parameters, downloadDirectory: downloadDirectoryURL)
        job.start(statusHandler: nil) { [weak self] (result, error) in
            guard let self = self else { return }
            if let result = result {
                self.offlineMapGenerationDidSucceed(with: result)
            } else if let error = error {
                self.offlineMapGenerationDidFail(with: error)
            }
        }
        self.generateOfflineMapJob = job
        let downloadProgressView = DownloadProgressView()
        downloadProgressView.delegate = self
        downloadProgressView.show(withStatus: "Generating offline map…", progress: 0)
        downloadProgressView.observedProgress = job.progress
        self.downloadProgressView = downloadProgressView
    }

    /// Called when the generate offline map job finishes successfully.
    ///
    /// - Parameter result: The result of the generate offline map job.
    func offlineMapGenerationDidSucceed(with result: AGSGenerateOfflineMapResult) {
        // Dismiss download progress view.
        downloadProgressView?.dismiss()
        downloadProgressView = nil

        // 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)" }

            let message: String = {
               let format = "The following error(s) occurred while generating the offline map:\n\n%@"
                return String(format: format, errorMessages.joined(separator: "\n"))
            }()
            presentAlert(title: "Offline Map Generated with Errors", message: message)
        }

        areaOfInterestView.isHidden = true
        mapView.map = result.offlineMap
        mapView.setViewpoint(AGSViewpoint(targetExtent: areaOfInterest))
        mapView.isUserInteractionEnabled = true
    }

    /// Called when the generate offline map job fails.
    ///
    /// - Parameter error: The error that caused the generation to fail.
    func offlineMapGenerationDidFail(with error: Error) {
        if (error as NSError).code != NSUserCancelledError {
            self.presentAlert(error: error)
        }
        self.generateButtonItem.isEnabled = true
        mapView.isUserInteractionEnabled = true
    }

    // MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()

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

extension GenerateOfflineMapBasemapByReferenceViewController: DownloadProgressViewDelegate {
    func downloadProgressViewDidCancel(_ downloadProgressView: DownloadProgressView) {
        downloadProgressView.observedProgress?.cancel()
        self.generateButtonItem.isEnabled = true
        mapView.isUserInteractionEnabled = true
    }
}

@IBDesignable
class GenerateOfflineMapBasemapByReferenceOverlayView: UIView {
    @IBInspectable var borderColor: UIColor? {
        get {
            return layer.borderColor.map(UIColor.init(cgColor:))
        }
        set {
            layer.borderColor = newValue?.cgColor
        }
    }
    @IBInspectable var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
}

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