Export vector tiles

View on GitHub
Sample viewer app

Export tiles from an online vector tile service.

Exporting vector tiles Successful export vector tiles

Use case

Field workers with limited network connectivity can use exported vector tiles as a basemap for use while offline.

How to use the sample

When the vector tiled layer loads, zoom in to the extent you want to export. The red box shows the extent that will be exported. Tap the "Export vector tiles" button to start exporting the vector tiles. An error will show if the extent is larger than the maximum limit allowed. When finished, a new map view will show the exported result.

How it works

  1. Create an AGSArcGISVectorTiledLayer, from the map's base layers.
  2. Create an AGSExportVectorTilesTask using the vector tiled layer's URL.
  3. Create default AGSExportVectorTilesParameters from the task, specifying extent and maximum scale.
  4. Create an AGSExportVectorTilesJob from the task using the parameters, specifying a vector tile cache path, and an item resource path. The resource path is required if you want to export the tiles with the style.
  5. Start the job, and once it completes successfully, get the resulting AGSExportVectorTilesResult.
  6. Get the AGSVectorTileCache and AGSItemResourceCache from the result to create an AGSArcGISVectorTiledLayer that can be displayed to the map view.

Relevant API

  • AGSArcGISVectorTiledLayer
  • AGSExportVectorTilesJob
  • AGSExportVectorTilesParameters
  • AGSExportVectorTilesResult
  • AGSExportVectorTilesTask
  • AGSItemResourceCache
  • AGSVectorTileCache

Additional information

Vector tiles have high drawing performance and smaller file size compared to regular tiled layers, due to consisting solely of points, lines, and polygons. However, in ArcGIS Runtime SDK they cannot be displayed in scenes. Visit ArcGIS for Developers to learn more about the characteristics of ArcGIS vector tiled layers.

Tags

cache, download, offline, vector

Sample Code

ExportVectorTilesViewController.swiftExportVectorTilesViewController.swiftVectorTilePackageViewController.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
// 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 ExportVectorTilesViewController: UIViewController {
    // MARK: Storyboard views

    /// The map view managed by the view controller.
    @IBOutlet var mapView: AGSMapView! {
        didSet {
            mapView.map = AGSMap(basemapStyle: .arcGISStreetsNight)
            // Set the viewpoint.
            mapView.setViewpoint(AGSViewpoint(latitude: 34.049, longitude: -117.181, scale: 1e4))
        }
    }

    /// A view to emphasize the extent of exported tile layer.
    @IBOutlet var extentView: UIView! {
        didSet {
            extentView.layer.borderColor = UIColor.red.cgColor
            extentView.layer.borderWidth = 2
        }
    }

    /// A bar button to initiate the download task.
    @IBOutlet var exportVectorTilesButton: UIBarButtonItem!
    @IBOutlet var progressView: UIProgressView!
    @IBOutlet var progressLabel: UILabel!
    @IBOutlet var progressParentView: UIView!
    @IBOutlet var cancelButton: UIButton!

    // MARK: Properties

    /// The resulting vector tiled layer.
    var vectorTiledLayer: AGSArcGISVectorTiledLayer?
    /// The extent of the map that is to be exported.
    var extent: AGSEnvelope?
    /// The export task to request the tile package with the same URL as the tile layer.
    var exportVectorTilesTask: AGSExportVectorTilesTask?
    /// An export job to download the tile package.
    var job: AGSExportVectorTilesJob? {
        didSet {
            // Remove key-value observation.
            progressObservation = nil
            exportVectorTilesButton.isEnabled = job == nil
            // Refresh the progress view according to the job status.
            updateProgressViewUI()
            // Observe the job's progress.
            progressView.observedProgress = job?.progress
            // Observe the localized description in order to update the text label.
            progressObservation = job?.progress.observe(\.localizedDescription, options: .initial) { [weak self] progress, _ in
                DispatchQueue.main.async {
                    // Update the progress label.
                    self?.progressLabel.text = progress.localizedDescription
                }
            }
        }
    }

    /// A URL to the temporary directory to temporarily store the exported vector tile package.
    let vtpkTemporaryURL: URL
    /// A URL to the temporary directory to temporarily store the style item resources.
    let styleTemporaryURL: URL
    /// A directory to temporarily store all items.
    let temporaryDirectory: URL

    /// Observation to track the export vector tiles job.
    private var progressObservation: NSKeyValueObservation?

    required init?(coder: NSCoder) {
        temporaryDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(ProcessInfo().globallyUniqueString)
        try? FileManager.default.createDirectory(at: temporaryDirectory, withIntermediateDirectories: false)
        vtpkTemporaryURL = temporaryDirectory
            .appendingPathComponent("myTileCache", isDirectory: false)
            .appendingPathExtension("vtpk")
        styleTemporaryURL = temporaryDirectory
            .appendingPathComponent("styleItemResources", isDirectory: true)
        super.init(coder: coder)
    }

    // MARK: Methods

    /// Initiate the `AGSExportVectorTilesTask` to download a tile package.
    /// - Parameters:
    ///   - exportTask: An `AGSExportVectorTilesTask` to run the export job.
    ///   - vectorTileCacheURL: A URL to where the tile package should be saved.
    func initiateDownload(exportTask: AGSExportVectorTilesTask, vectorTileCacheURL: URL) {
        // Set the max scale parameter to 10% of the map's scale to limit the
        // number of tiles exported to within the vector tiled layer's max tile export limit.
        let maxScale = mapView.mapScale * 0.1
        // Get current area of interest marked by the extent view.
        let areaOfInterest = envelope(for: extentView)
        // Get the parameters by specifying the selected area and vector tiled layer's max scale as maxScale.
        exportTask.defaultExportVectorTilesParameters(withAreaOfInterest: areaOfInterest, maxScale: maxScale) { [weak self] parameters, error in
            guard let self = self, let exportVectorTilesTask = self.exportVectorTilesTask else { return }
            if let params = parameters {
                // Start exporting the tiles with the resulting parameters.
                self.exportVectorTiles(exportTask: exportVectorTilesTask, parameters: params, vectorTileCacheURL: vectorTileCacheURL)
            } else if let error = error {
                self.presentAlert(error: error)
            }
        }
    }

    /// Export vector tiles with the `AGSExportVectorTilesJob` from the export task.
    /// - Parameters:
    ///   - exportTask: An `AGSExportVectorTilesTask` to run the export job.
    ///   - parameters: The parameters of the export task.
    ///   - vectorTileCacheURL: A URL to where the tile package is saved.
    func exportVectorTiles(exportTask: AGSExportVectorTilesTask, parameters: AGSExportVectorTilesParameters, vectorTileCacheURL: URL) {
        // Create the job with the parameters and download URLs.
        let job = exportTask.exportVectorTilesJob(with: parameters, vectorTileCacheDownloadFileURL: vtpkTemporaryURL, itemResourceCacheDownloadDirectory: styleTemporaryURL)
        self.job = job
        // Start the job.
        job.start(statusHandler: nil) { [weak self] (result, error) in
            guard let self = self else { return }
            self.job = nil
            if let result = result,
               let tileCache = result.vectorTileCache,
               let itemResourceCache = result.itemResourceCache {
                self.updateProgressViewUI()
                // Create the vector tiled layer with the tile cache and item resource cache.
                self.vectorTiledLayer = AGSArcGISVectorTiledLayer(vectorTileCache: tileCache, itemResourceCache: itemResourceCache)
                // Set the extent.
                self.extent = parameters.areaOfInterest as? AGSEnvelope
                self.performSegue(withIdentifier: "showResult", sender: nil)
            } else if let error = error {
                let nsError = error as NSError
                if !(nsError.domain == NSCocoaErrorDomain && nsError.code == NSUserCancelledError) {
                    self.presentAlert(error: error)
                }
            }
        }
    }

    /// Get the extent within the extent view for generating a vector tile package.
    func envelope(for view: UIView) -> AGSEnvelope {
        let frame = mapView.convert(view.frame, from: self.view)

        let minPoint = mapView.screen(toLocation: CGPoint(x: frame.minX, y: frame.minY))
        let maxPoint = mapView.screen(toLocation: CGPoint(x: frame.maxX, y: frame.maxY))
        let extent = AGSEnvelope(min: minPoint, max: maxPoint)
        return extent
    }

    /// Update the progress view accordingly.
    func updateProgressViewUI() {
        let isJobNil = job == nil
        mapView.interactionOptions.isEnabled = isJobNil
        progressParentView.isHidden = isJobNil
    }

    /// Remove temporary files that are created for each job.
    func removeTemporaryFiles() {
        try? FileManager.default.removeItem(at: vtpkTemporaryURL)
        try? FileManager.default.removeItem(at: styleTemporaryURL)
    }

    // MARK: Actions

    @IBAction func exportTilesBarButtonTapped(_ sender: UIBarButtonItem) {
        if let exportVectorTilesTask = exportVectorTilesTask,
           let vectorTileSourceInfo = exportVectorTilesTask.vectorTileSourceInfo,
           vectorTileSourceInfo.exportTilesAllowed {
            // Try to download when exporting tiles is allowed.
            initiateDownload(exportTask: exportVectorTilesTask, vectorTileCacheURL: vtpkTemporaryURL)
        } else {
            presentAlert(title: "Error", message: "Exporting tiles is not supported for the service.")
        }
    }

    @IBAction func cancelAction() {
        // Cancel export vector tiles job and remove the temporary files.
        job?.progress.cancel()
        removeTemporaryFiles()
    }

    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let navController = segue.destination as? UINavigationController,
           let rootController = navController.viewControllers.first as? VectorTilePackageViewController {
            // Display the view controller as a formsheet - specified for iPads.
            rootController.modalPresentationStyle = .formSheet
            rootController.isModalInPresentation = true
            rootController.tiledLayerResult = vectorTiledLayer
            rootController.extent = extent
            rootController.delegate = self
        }
    }

    // MARK: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.map?.load { [weak self] _ in
            guard let self = self else { return }
            // Obtain the vector tiled layer and its URL from the baselayers.
            guard let vectorTiledLayer = self.mapView.map?.basemap.baseLayers.firstObject as? AGSArcGISVectorTiledLayer,
                  let vectorTiledLayerURL = vectorTiledLayer.url else { return }
            // The export task to request the tile package with the same URL as the tile layer.
            let exportVectorTilesTask = AGSExportVectorTilesTask(url: vectorTiledLayerURL)
            self.exportVectorTilesTask = exportVectorTilesTask
            exportVectorTilesTask.load { [weak self] error in
                guard let self = self else { return }
                if let error = error {
                    self.presentAlert(error: error)
                } else {
                    self.exportVectorTilesButton.isEnabled = true
                }
            }
        }
        // Add the source code button item to the right of navigation bar.
        (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ExportVectorTilesViewController", "VectorTilePackageViewController"]
    }

    deinit {
        try? FileManager.default.removeItem(at: temporaryDirectory)
    }
}

extension ExportVectorTilesViewController: VectorTilePackageViewControllerDelegate {
    func vectorTilePackageViewControllerDidFinish(_ controller: VectorTilePackageViewController) {
        // Remove the downloaded vector tile package files after finishing viewing them.
        removeTemporaryFiles()
    }
}

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