Skip to content
View on GitHub

Create and save a map as a web map item to an ArcGIS portal.

Image of create and save map

Use case

Maps can be created programmatically in code and then serialized and saved as an ArcGIS portal item. In this case, the portal item is a web map which can be shared with others and opened in various applications and APIs throughout the platform, such as ArcGIS Pro, ArcGIS Online, the JavaScript API, and Field Maps.

How to use the sample

When you run the sample, you will be challenged for an ArcGIS Online login. Enter a username and password for an ArcGIS Online named user account (such as your ArcGIS for Developers account). Then, choose the basemap and layers for your new map. To save the map, add a title, tags, and description (optional), and a folder on your portal (you will need to create one in your portal's My Content section if you don't already have one). Click the Save button to save the map to the chosen folder.

How it works

  1. Set up the authenticator the manage authentication challenges.
  2. Create a new Portal with an authenticated connection and load it.
  3. Log in to the portal.
  4. Access the PortalUser.Content with portal.user.content, to get the user's list of portal folders.
  5. Create a Map with the specified BasemapStyle and operational data.
  6. Call Map.save(to:title:forceSaveToSupportedVersion:folder:description:thumbnail:tags:extent:) to save the configured Map with the specified title, tags, description, and folder to the portal.

Relevant API

  • ArcGISMapImageLayer
  • BasemapStyle
  • Map
  • Portal

Tags

ArcGIS Online, ArcGIS Pro, portal, publish, share, web map

Sample Code

CreateAndSaveMapView.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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 // Copyright 2025 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 ArcGISToolkit import SwiftUI  /// A view that allows a user to create a map and save it to a portal. struct CreateAndSaveMapView: View {  /// The authenticator to handle authentication challenges.  @StateObject private var authenticator = Authenticator()   /// The portal to save the map to.  @State private var portal = Portal(  url: URL(string: "https://www.arcgis.com")!,  connection: .authenticated  )   /// The map that we will save to the portal.  @State private var map: Map?   /// The error that occurred, if any, when trying to save the map to the portal.  @State private var error: Error?   /// The status of the sample workflow.  @State private var status: Status = .loadingPortal   /// The API key to use temporarily while using OAuth.  @State private var apiKey: APIKey?   /// The portal user's folders that you can save the map to.  @State private var folders: [PortalFolder] = []   var body: some View {  VStack {  if let map {  MapView(map: map)  } else {  switch status {  case .loadingPortal:  ProgressView("Loading portal...")  case .failedToLoadPortal:  ContentUnavailableView(  "Error",  systemImage: "exclamationmark.triangle",  description: Text("Portal could not be loaded.")  )  case .creatingMap, .savingMapToPortal:  SaveMapForm(portal: portal, folders: folders, status: $status)  case .failedToSaveMap:  ContentUnavailableView(  "Error",  systemImage: "exclamationmark.triangle",  description: Text("Failed to save map to portal.")  )  case .mapSavedSuccessfully:  ContentUnavailableView {  Label("Success", systemImage: "checkmark.circle")  } description: {  Text("Map saved successfully to the portal.")  } actions: {  Button("Delete Map From Portal") {  Task { await deleteFromPortal() }  }  .buttonStyle(.borderedProminent)  }  case .deletingMap:  ProgressView("Deleting map...")  case .deletedSuccessfully:  ContentUnavailableView(  "Success",  systemImage: "checkmark.circle",  description: Text("Map successfully deleted from the portal.")  )  case .failedToDelete:  ContentUnavailableView(  "Error",  systemImage: "exclamationmark.triangle",  description: Text("Failed to delete map from portal.")  )  }  }  }  .task {  // Load the portal and get the folders.  do {  try await portal.load()  let content = try await portal.user?.content  if let folders = content?.folders {  self.folders = Array(folders.prefix(10))  }  status = .creatingMap  } catch {  status = .failedToLoadPortal  }  }  .errorAlert(presentingError: $error)  .authenticator(authenticator)  .onAppear {  // Temporarily unsets the API key for this sample to use OAuth.  apiKey = ArcGISEnvironment.apiKey  ArcGISEnvironment.apiKey = nil   // Setup the authenticator.  setupAuthenticator()  }  .onTeardown {  // Reset the challenge handlers and clear credentials  // when the view disappears so that user is prompted to enter  // credentials every time the sample is run, and to clean  // the environment for other samples.  await teardownAuthenticator()   // Sets the API key back to the original value.  ArcGISEnvironment.apiKey = apiKey  }  }   /// Deletes the saved map from the portal.  private func deleteFromPortal() async {  guard case .mapSavedSuccessfully(let map) = status else {  return  }  do {  status = .deletingMap  try await portal.user?.delete(map.item! as! PortalItem)  status = .deletedSuccessfully  } catch {  status = .failedToDelete  }  } }  private extension CreateAndSaveMapView {  /// A form that allows the user fill out properties for a map that they  /// want to create and save to a portal.  struct SaveMapForm: View {  /// The portal to save the map to.  let portal: Portal   /// The folders that the user can save the map to.  let folders: [PortalFolder]   /// The status of the workflow of creating and saving a map.  @Binding var status: Status   /// The title of the new map.  @State private var title: String = ""   /// The tags for the map.  @State private var tags: String = ""   /// A description of the map.  @State private var description: String = ""   /// The basemap that the user chose for the new map.  @State private var basemap: BasemapOption = .topographic   /// The operational data that the user chooses to display on the map.  @State private var operationalData: OperationalDataOption = .none   /// The folder that the user chose to save the map to.  @State private var folder: PortalFolder?   /// The map to save to the portal.  @State private var map = Map(basemapStyle: BasemapOption.topographic.style)   /// The viewpoint of the map view, this will be set as the initial viewpoint  /// of the map saved to the portal.  @State private var viewpoint: Viewpoint?   var body: some View {  MapViewReader { mapViewProxy in  Form {  Section("Create Map") {  TextField("Title", text: $title)  TextField("Tags", text: $tags)  .autocorrectionDisabled()  TextField("Description", text: $description)  Picker("Folder", selection: $folder) {  ForEach(folders, id: \.self) { folder in  Text(folder.title)  .tag(folder)  }  Text("None")  .tag(Optional<PortalFolder>.none)  }  Picker("Basemap", selection: $basemap) {  ForEach(BasemapOption.allCases, id: \.self) { value in  Text(value.label)  }  }  Picker("Operational Data", selection: $operationalData) {  ForEach(OperationalDataOption.allCases, id: \.self) { value in  Text(value.label)  }  }  }  Section {  MapView(map: map)  .onViewpointChanged(kind: .centerAndScale) { viewpoint = $0 }  .highPriorityGesture(DragGesture())  .frame(height: 300)  }  Section {  Button {  Task { await save(mapViewProxy: mapViewProxy) }  } label: {  if status == .savingMapToPortal {  HStack {  Text("Saving")  ProgressView()  }  } else {  Text("Save to Portal")  }  }  .disabled(title.isEmpty)  .frame(maxWidth: .infinity)  }  }  .disabled(status == .savingMapToPortal)  .onChange(of: basemap) { map.basemap = Basemap(style: basemap.style) }  .onChange(of: operationalData) {  map.removeAllOperationalLayers()  if let layer = operationalData.layer {  map.addOperationalLayer(layer)  }  }  }  }   /// Saves the map to the portal.  private func save(mapViewProxy: MapViewProxy) async {  do {  // Set the status appropriately.  status = .savingMapToPortal  // Set the initial viewpoint of the map.  map.initialViewpoint = viewpoint  // Try to save the map.  try await map  .save(  to: portal,  title: title,  forceSaveToSupportedVersion: false,  folder: folder,  description: description,  thumbnail: try? await mapViewProxy.exportImage(),  tags: tags.components(separatedBy: ",")  )  // Set the status if successful.  status = .mapSavedSuccessfully(map)  } catch {  // Set the status if failed.  status = .failedToSaveMap  }  }  } }  private extension CreateAndSaveMapView.SaveMapForm {  /// The basemap options for our new map.  /// These were arbitrarily chosen for the purpose of the sample.  enum BasemapOption: CaseIterable {  /// A topographic map.  case topographic  /// A streets map.  case streets  /// A night-themed map.  case night   /// The corresponding basemap style.  var style: Basemap.Style {  switch self {  case .topographic:  .arcGISTopographic  case .streets:  .arcGISStreets  case .night:  .arcGISNavigationNight  }  }   /// The label for user interface purposes.  var label: String {  switch self {  case .topographic:  "Topographic"  case .streets:  "Streets"  case .night:  "Night Navigation"  }  }  }   /// The operational data options for our new map.  /// These were arbitrarily chosen for the purpose of the sample.  enum OperationalDataOption: CaseIterable {  /// No operational data.  case none  /// Operational data for time zones.  case timeZones  /// U.S. census tracts.  case census   /// The url of the layer.  private var url: URL? {  switch self {  case .none:  nil  case .timeZones:  URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer")!  case .census:  URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer")!  }  }   /// The map image layer that corresponds to the option.  var layer: ArcGISMapImageLayer? {  url.map(ArcGISMapImageLayer.init(url:))  }   /// The label for user interface purposes.  var label: String {  switch self {  case .none:  "None"  case .timeZones:  "Time Zone"  case .census:  "Census"  }  }  } }  private extension CreateAndSaveMapView {  /// The status of the create and save workflow.  enum Status: Equatable {  /// The portal is loading.  case loadingPortal  /// The portal failed to load.  case failedToLoadPortal  /// The map is being created.  case creatingMap  /// The map is being saved to the portal.  case savingMapToPortal  /// The map failed to save to the portal.  case failedToSaveMap  /// The map was saved successfully to the portal.  case mapSavedSuccessfully(Map)  /// The map is being deleted from the portal.  case deletingMap  /// The map was successfully deleted from the portal.  case deletedSuccessfully  /// The map failed to delete from the portal.  case failedToDelete  } }  private extension CreateAndSaveMapView {  /// Sets up the authenticator to handle challenges.  func setupAuthenticator() {  // Setting the challenge handlers here when the model is created so user is prompted to enter  // credentials every time trying the sample. In real world applications, set challenge  // handlers at the start of the application.   // Sets authenticator as ArcGIS and Network challenge handlers to handle authentication  // challenges.  ArcGISEnvironment.authenticationManager.handleChallenges(using: authenticator)   // In your application you may want to uncomment this code to persist  // credentials in the keychain.  // setupPersistentCredentialStorage()  }   /// Stops the authenticator from handling the challenges and clears credentials.  func teardownAuthenticator() async {  // Resets challenge handlers.  ArcGISEnvironment.authenticationManager.handleChallenges(using: nil)   // In your application, code may need to run at a different  // point in time based on the workflow desired. For example, it  // might make sense to remove credentials when the user taps  // a "sign out" button.  await ArcGISEnvironment.authenticationManager.revokeOAuthTokens()  await ArcGISEnvironment.authenticationManager.clearCredentialStores()  }   /// Sets up new ArcGIS and Network credential stores that will be persisted in the keychain.  private func setupPersistentCredentialStorage() {  Task {  try await ArcGISEnvironment.authenticationManager.setupPersistentCredentialStorage(  access: .whenUnlockedThisDeviceOnly  )  }  } }  #Preview {  CreateAndSaveMapView() }

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