Apply scheduled updates to preplanned map area

View on GitHub

Apply scheduled updates to a downloaded preplanned map area.

Image of Apply scheduled updates to preplanned map area sample

Use case

With scheduled updates, the author can update the features within the preplanned areas on the service once, and multiple end-users can request these updates to bring their local copies up to date with the most recent state. Importantly, any number of end-users can download the same set of cached updates which means that this workflow is extremely scalable for large operations where you need to minimize load on the server.

This workflow can be used by survey workers operating in remote areas where network connectivity is not available. The workers could download mobile map packages to their individual devices and perform their work normally. Once they regain Internet connectivity, the mobile map packages can be updated to show any new features that have been added to the online service.

How to use the sample

When the sample loads, it will display an offline map, check for available updates, and show update availability and size. Tap the button to apply the updates to the local offline map and show the results.

How it works

  1. Create an OfflineMapSyncTask object with your offline map.
  2. Get an OfflineMapUpdatesInfo instance from the task to check for update availability and update size.
  3. Get the default OfflineMapSyncParameters from the task.
  4. Set the parameters to download all available updates.
  5. Use the parameters to create an OfflineMapSyncJob object.
  6. Start the job and get the results once it completes successfully.
  7. Check if the mobile map package needs to be reopened and do so if necessary.
  8. Display the updated offline map to see the changes.

Relevant API

  • MobileMapPackage
  • OfflineMapSyncJob
  • OfflineMapSyncParameters
  • OfflineMapSyncResult
  • OfflineMapSyncTask
  • OfflineMapUpdatesInfo

About the data

The data in this sample shows the roads and trails in the Canyonlands National Park, Utah. Data by U.S. National Parks Service. No claim to original U.S. Government works.

Additional information

Note: preplanned areas using the Scheduled Updates workflow are read-only. For preplanned areas that can be edited on the end-user device, see the Download preplanned map area sample. For more information about offline workflows, see Offline maps, scenes, and data on the Esri Developer website.

Tags

offline, pre-planned, preplanned, synchronize, update

Sample Code

ApplyScheduledUpdatesToPreplannedMapAreaView.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
// Copyright 2024 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

struct ApplyScheduledUpdatesToPreplannedMapAreaView: View {
    /// The view model for the sample.
    @StateObject private var model = Model()

    /// A Boolean value indicating whether the alert for
    /// scheduled updates is presented.
    @State private var updatesAlertIsPresented = false

    /// A Boolean value indicating whether the alert for
    /// no available updates is presented.
    @State private var noUpdatesAlertIsPresented = false

    /// The error shown in the error alert.
    @State private var error: Error?

    var body: some View {
        MapView(map: model.map)
            .errorAlert(presentingError: $error)
            .task {
                do {
                    try await model.setUp()
                } catch {
                    self.error = error
                }
            }
            .onChange(of: model.updatesInfo == nil) { _ in
                guard let updatesInfo = model.updatesInfo else { return }
                // Handle the updates info from the offline map sync task.
                handleUpdatesInfo(updatesInfo)
            }
            .overlay {
                // Show a progress view for the offline map sync job that downloads
                // the available updates.
                if let progress = model.offlineMapSyncJob?.progress {
                    VStack(spacing: 16) {
                        ProgressView(progress)
                            .progressViewStyle(.linear)
                            .frame(maxWidth: 200)
                    }
                    .padding()
                    .background(.regularMaterial)
                    .clipShape(RoundedRectangle(cornerRadius: 15))
                    .shadow(radius: 3)
                }
            }
            .alert("Scheduled Updates Available", isPresented: $updatesAlertIsPresented) {
                Button("Cancel", role: .cancel) {}
                Button("Apply") {
                    Task {
                        do {
                            try await model.applyScheduledUpdates()
                        } catch {
                            self.error = error
                        }
                    }
                }
            } message: {
                // Get the download size for the update.
                let downloadSizeString = ByteCountFormatter.string(
                    from: Measurement(
                        value: Double(model.updatesInfo?.scheduledUpdatesDownloadSize ?? .zero),
                        unit: .bytes
                    ),
                    countStyle: .file
                )
                Text("A \(downloadSizeString) update is available. Would you like to apply it?")
            }
            .alert("Scheduled Updates Unavailable", isPresented: $noUpdatesAlertIsPresented) {
            } message: {
                Text("There are no updates available.")
            }
    }

    /// Displays different alerts based on the offline map updates info.
    /// - Parameter info: The updates info from the offline map sync task.
    private func handleUpdatesInfo(_ info: OfflineMapUpdatesInfo) {
        switch info.downloadAvailability {
        case .available:
            updatesAlertIsPresented = true
        case .noneAvailable, .indeterminate:
            noUpdatesAlertIsPresented = true
        @unknown default:
            fatalError("Unknown offline map updates info")
        }
    }
}

private extension ApplyScheduledUpdatesToPreplannedMapAreaView {
    /// The model used to store the geo model and other expensive objects
    /// used in this view.
    @MainActor
    class Model: ObservableObject {
        /// A map from the mobile map package.
        @Published private(set) var map = Map()

        /// The sync job used to apply updates to the offline map.
        @Published private(set) var offlineMapSyncJob: OfflineMapSyncJob?

        /// The information on the available updates for an offline map.
        @Published private(set) var updatesInfo: OfflineMapUpdatesInfo?

        /// The temporary URL to store the mobile map package.
        private let temporaryMobileMapPackageURL = FileManager
            .createTemporaryDirectory()
            .appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString)

        /// The mobile map package used by this sample.
        private var mobileMapPackage: MobileMapPackage?

        /// The sync task used to check for scheduled updates.
        private var offlineMapSyncTask: OfflineMapSyncTask?

        /// Loads the offline map and sets up the sync task.
        func setUp() async throws {
            // Open and load the mobile map package from local disk.
            let mobileMapPackageURL = Bundle.main.url(forResource: "canyonlands", withExtension: nil)!
            // Copy the map package from the bundle so updates can be applied.
            try FileManager.default.copyItem(
                at: mobileMapPackageURL,
                to: temporaryMobileMapPackageURL
            )
            let mobileMapPackage = MobileMapPackage(fileURL: temporaryMobileMapPackageURL)
            try await mobileMapPackage.load()
            self.mobileMapPackage = mobileMapPackage

            // Create a sync task from the first map of the map package.
            map = mobileMapPackage.maps.first!
            let offlineMapSyncTask = OfflineMapSyncTask(map: map)
            self.offlineMapSyncTask = offlineMapSyncTask

            // Get high-level information on the available updates.
            updatesInfo = try await offlineMapSyncTask.checkForUpdates()
        }

        /// Applies available updates to the offline map.
        func applyScheduledUpdates() async throws {
            guard let mobileMapPackage, let offlineMapSyncTask else { return }

            // Create default parameters and the sync job from the sync task.
            let parameters = try await offlineMapSyncTask.makeDefaultOfflineMapSyncParameters()
            let offlineMapSyncJob = offlineMapSyncTask.makeSyncOfflineMapJob(parameters: parameters)
            self.offlineMapSyncJob = offlineMapSyncJob

            // Start the job.
            offlineMapSyncJob.start()
            // Await the output of the job and assigns the result.
            let output = try await offlineMapSyncJob.output
            // Set the job to nil to release the reference.
            self.offlineMapSyncJob = nil

            // Return if no reopen is required to see the updated map package.
            guard output.mobileMapPackageReopenIsRequired else { return }

            // Close then reload the updated map package.
            mobileMapPackage.close()
            let updatedMobileMapPackage = MobileMapPackage(fileURL: temporaryMobileMapPackageURL)
            try await updatedMobileMapPackage.load()
            map = updatedMobileMapPackage.maps.first!
            self.mobileMapPackage = updatedMobileMapPackage
        }

        deinit {
            // Remove the temporary directory.
            let temporaryDirectory = temporaryMobileMapPackageURL.deletingLastPathComponent()
            try? FileManager.default.removeItem(at: temporaryDirectory)
        }
    }
}

private extension FileManager {
    /// Creates a temporary directory.
    /// - Returns: The URL of the created directory.
    static func createTemporaryDirectory() -> URL {
        // swiftlint:disable:next force_try
        try! FileManager.default.url(
            for: .itemReplacementDirectory,
            in: .userDomainMask,
            appropriateFor: FileManager.default.temporaryDirectory,
            create: true
        )
    }
}

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