Take a web map offline with additional options for each layer.
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
- Load a web map from an
AGSPortalItem
. Authenticate with the portal if required. - Create an
AGSOfflineMapTask
with the map. - Generate default task parameters using the extent area you want to download with the
AGSOfflineMapTask.defaultGenerateOfflineMapParameters(withAreaOfInterest:completion:)
method. - Generate additional "override" parameters using the default parameters with the
AGSOfflineMapTask.generateOfflineMapParameterOverrides(with:completion:)
method. - For the basemap:
- Get the parameters
AGSOfflineMapParametersKey
for the basemap layer. - Get the
AGSExportTileCacheParameters
for the basemap layer fromAGSGenerateOfflineMapParameterOverrides exportTileCacheParameters[key]
with the key above. - Set the level IDs you want to download by setting the
levelIDs
property ofAGSExportTileCacheParameters
. - To buffer the extent, set a buffered geometry to the
areaOfInterest
property ofAGSExportTileCacheParameters
, where the buffered geometry can be calculated with theAGSGeometryEngine
.
- Get the parameters
- To remove operational layers from the download:
- Create an
AGSOfflineMapParametersKey
with the operational layer. - Use the key to obtain the relevant
AGSGenerateGeodatabaseParameters
from thegenerateGeodatabaseParameters
property ofAGSGenerateOfflineMapParameterOverrides
. - Loop through each
AGSGenerateLayerOption
and remove it from the geodatabase parameters'layerOptions
if the layer option's ID matches theserviceLayerID
.
- Create an
- 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.
- To not crop a layer's features to the extent of the offline map (default is true):
- Set
useGeometry
property ofAGSGenerateLayerOption
to false.
- Set
- Create an
AGSGenerateOfflineMapJob
withAGSOfflineMapTask.generateOfflineMapJob(with:parameterOverrides:downloadDirectory:)
. Start the job withAGSGenerateOfflineMapJob.start(statusHandler:completion:)
. - 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
//
// 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")
}
}