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
Create a Map instance with a PortalItem.
Create an OfflineMapTask instance with the online map.
Create GenerateOfflineMapParameters parameters for the offline map task with OfflineMapTask.makeDefaultGenerateOfflineMapParameters(areaOfInterest:).
Create a GenerateOfflineMapJob with OfflineMapTask.makeGenerateOfflineMapJob(parameters:downloadDirectory:), using the parameters and specifying a download directory URL.
Start the job and await its output.
Get the offline map from the output when the job successfully finishes.
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
GenerateOfflineMapView.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// Copyright 2022 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//// https://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 ArcGIS
import SwiftUI
structGenerateOfflineMapView: View{
/// A Boolean value indicating whether the job is generating an offline map.@Stateprivatevar isGeneratingOfflineMap =false/// A Boolean value indicating whether the job is cancelling.@Stateprivatevar isCancellingJob =false/// The view model for this sample.@StateObjectprivatevar model =Model()
var body: someView {
GeometryReader { geometry inMapViewReader { mapView inMapView(map: model.offlineMap ?? model.onlineMap)
.interactionModes(isGeneratingOfflineMap ? [] : [.pan, .zoom])
.alert(isPresented: $model.isShowingAlert, presentingError: model.error)
.task {
await model.initializeOfflineMapTask()
}
.onDisappear {
Task { await model.cancelJob() }
}
.overlay {
Rectangle()
.stroke(.red, lineWidth: 2)
.padding(EdgeInsets(top: 20, leading: 20, bottom: 44, trailing: 20))
.opacity(model.offlineMap ==nil?1 : 0)
}
.overlay {
if isGeneratingOfflineMap,
let progress = model.generateOfflineMapJob?.progress {
VStack(spacing: 16) {
ProgressView(progress)
.progressViewStyle(.linear)
.frame(maxWidth: 200)
Button("Cancel") {
isCancellingJob =true }
.disabled(isCancellingJob)
.task(id: isCancellingJob) {
// Ensures cancelling the job is true.guard isCancellingJob else { return }
// Cancels the job.await model.cancelJob()
// Sets cancelling the job and generating an// offline map to false. isCancellingJob =false isGeneratingOfflineMap =false }
}
.padding()
.background(.regularMaterial)
.clipShape(RoundedRectangle(cornerRadius: 15))
.shadow(radius: 3)
}
}
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button("Generate Offline Map") {
isGeneratingOfflineMap =true }
.disabled(model.isGenerateDisabled || isGeneratingOfflineMap)
.task(id: isGeneratingOfflineMap) {
// Ensures generating an offline map is true.guard isGeneratingOfflineMap else { return }
// Creates a rectangle from the area of interest.let viewRect = geometry.frame(in: .local).inset(
by: UIEdgeInsets(
top: 20,
left: geometry.safeAreaInsets.leading +20,
bottom: 44,
right: -geometry.safeAreaInsets.trailing +20 )
)
// Creates an envelope from the rectangle.guardlet extent = mapView.envelope(fromViewRect: viewRect) else { return }
// Generates an offline map.await model.generateOfflineMap(extent: extent)
// Sets generating an offline map to false. isGeneratingOfflineMap =false }
}
}
}
}
}
}
privateextensionGenerateOfflineMapView{
/// The view model for this sample.@MainActorclassModel: ObservableObject{
/// The offline map that is generated.@Publishedvar offlineMap: Map!
/// A Boolean value indicating whether the generate button is disabled.@Publishedvar isGenerateDisabled =true/// A Boolean value indicating whether to show an alert.@Publishedvar isShowingAlert =false/// The error shown in the alert.@Publishedvar error: Error? {
didSet { isShowingAlert = error !=nil }
}
/// The generate offline map job.@Publishedvar generateOfflineMapJob: GenerateOfflineMapJob!
/// The offline map task.privatevar offlineMapTask: OfflineMapTask!
/// A URL to a temporary directory where the offline map files are stored.privatelet temporaryDirectory = makeTemporaryDirectory()
/// A portal item displaying the Naperville, IL water network.privatelet napervillePortalItem =PortalItem(
portal: .arcGISOnline(connection: .anonymous),
id: PortalItem.ID("acc027394bc84c2fb04d1ed317aac674")! )
/// The online map that is loaded from a portal item.let onlineMap: Mapinit() {
// Initializes the online map. onlineMap =Map(item: napervillePortalItem)
}
deinit {
// Removes the temporary directory.try?FileManager.default.removeItem(at: temporaryDirectory)
}
/// Initializes the offline map task.funcinitializeOfflineMapTask()async {
do {
// Waits for the online map to load.tryawait onlineMap.load()
offlineMapTask =OfflineMapTask(onlineMap: onlineMap)
isGenerateDisabled =false } catch {
self.error = error
}
}
/// Creates the generate offline map parameters./// - Parameter areaOfInterest: The area of interest to create the parameters for./// - Returns: A `GenerateOfflineMapParameters` if there are no errors. Otherwise, it returns `nil`,privatefuncmakeGenerateOfflineMapParameters(areaOfInterest: Envelope)async -> GenerateOfflineMapParameters? {
do {
// Returns the default parameters for the offline map task.returntryawait offlineMapTask.makeDefaultGenerateOfflineMapParameters(areaOfInterest: areaOfInterest)
} catch {
self.error = error
returnnil }
}
/// Generates the offline map./// - Parameter extent: The area of interest's envelope to generate an offline map for.funcgenerateOfflineMap(extent: Envelope)async {
// Disables the generate offline map button. isGenerateDisabled =true// Creates the default parameters for the offline map task.guardlet parameters =await makeGenerateOfflineMapParameters(areaOfInterest: extent) else {
isGenerateDisabled =falsereturn }
// Creates the generate offline map job based on the parameters. generateOfflineMapJob = offlineMapTask.makeGenerateOfflineMapJob(
parameters: parameters,
downloadDirectory: temporaryDirectory
)
// Starts the job. generateOfflineMapJob.start()
defer {
generateOfflineMapJob =nil isGenerateDisabled = offlineMap !=nil }
do {
// Awaits the output of the job.let output =tryawait generateOfflineMapJob.output
// Sets the offline map to the output's offline map. offlineMap = output.offlineMap
// Sets the initial viewpoint of the offline map. offlineMap.initialViewpoint =Viewpoint(targetExtent: extent.expanded(by: 0.8))
} catchisCancellationError {
// Does nothing if the error is a cancellation error. } catch {
// Shows an alert with the error if the job fails.self.error = error
}
}
/// Cancels the generate offline map job.funccancelJob()async {
// Cancels the generate offline map job.await generateOfflineMapJob?.cancel()
generateOfflineMapJob =nil }
/// Creates a temporary directory.privatestaticfuncmakeTemporaryDirectory() -> URL {
// swiftlint:disable:next force_trytry!FileManager.default.url(
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: Bundle.main.bundleURL,
create: true )
}
}
}
privateextensionMapViewProxy{
/// Creates an envelope from the given rectangle./// - Parameter viewRect: The rectangle to create an envelope of./// - Returns: An envelope of the given rectangle.funcenvelope(fromViewRectviewRect: CGRect) -> Envelope? {
guardlet min = location(fromScreenPoint: CGPoint(x: viewRect.minX, y: viewRect.minY)),
let max = location(fromScreenPoint: CGPoint(x: viewRect.maxX, y: viewRect.maxY)) else {
returnnil }
returnEnvelope(min: min, max: max)
}
}
privateextensionEnvelope{
/// Expands the envelope by a given factor.funcexpanded(byfactor: Double) -> Envelope {
let builder =EnvelopeBuilder(envelope: self)
builder.expand(factor: factor)
return builder.toGeometry()
}
}