Skip to content

Show portal user info

View on GitHub

Retrieve a user's details via a Portal.

Image of show portal user info sample

Use case

Portal information can be used to build a user interface. For example, the portal user's thumbmnail can be shown to indicate that they are currently logged in.

How to use the sample

Enter your ArcGIS Online credentials for the specified URL.

How it works

  1. Present the user with an editable text field for entering a portal URL.
  2. Create and load a portal with the URL.
  3. If the portal is secured, it may potentially issue an authentication challenge.
  4. Display the desired portal info once loading has successfully completed. Otherwise, if loading failed, display the error.
  5. Upon successful login, get a PortalUser using portal.user. Get user attributes using:
    • portalUser.portalName
    • portalUser.username
    • portalUser.email
    • portalUser.creationDate
    • portalUser.thumbnail.image
  6. The "Sign out" button clears any saved credentials.

Relevant API

  • OAuthUserConfiguration
  • Portal
  • PortalInfo
  • PortalUser

About the data

This sample signs into your ArcGIS online account and displays the user's profile information.

Tags

account, avatar, bio, cloud and portal, email, login, picture, profile, user, username

Sample Code

ShowPortalUserInfoView.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
// 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

struct ShowPortalUserInfoView: View {
    /// The data model that helps determine the view.
    @State private var model = Model()
    /// The error shown in the error alert.
    @State private var error: Error?

    var body: some View {
        VStack {
            // Shows field for custom portal urls as well as Sign In / Out.
            PortalDetailsView(
                url: $model.portalURLString,
                model: $model,
                // Update the model when the portal URL is changed by the user.
                onSetUrl: {
                    model.portalURLString = $0
                },
                // Sign out the user.
                onSignOut: {
                    Task {
                        await model.signOut()
                    }
                },
                // Load the user's portal data when sign in is triggered.
                onLoadPortal: {
                    Task {
                        await loadUser()
                    }
                }
            )
            // If there is no current user, show that the user profile will display here when complete.
            if model.portalUser == nil {
                ContentUnavailableView(
                    "Portal User Information",
                    systemImage: "person.crop.circle.dashed",
                    description: Text("Your portal user information will be displayed here.")
                )
                // Otherwise show the user information that was loaded.
            } else {
                InfoScreen(model: $model)
            }
            Spacer()
        }
#if targetEnvironment(macCatalyst)
        .frame(maxWidth: 540)
#endif
        .frame(maxHeight: .infinity)
        .padding(.horizontal)
        // Set up the authenticator when the view appears.
        .onAppear(perform: model.setAuthenticator)
        // Clean up authenticator and credentials when the view disappears.
        .onTeardown {
            await model.clearAuthenticator()
        }
        // Attach the authenticator to the view for handling authentication challenges.
        .authenticator(model.authenticator)
        .errorAlert(presentingError: $error)
    }

    /// Asynchronously loads the portal user information.
    private func loadUser() async {
        do {
            try await model.loadPortalUser()
        } catch {
            // If an error occurs, store the error to present an alert.
            self.error = error
        }
    }
}

private extension ShowPortalUserInfoView {
    @MainActor
    @Observable
    class Model {
        /// The authenticator to handle authentication challenges.
        @ObservationIgnored var authenticator: Authenticator
        /// The API key to use temporarily while using OAuth.
        @ObservationIgnored private var apiKey: APIKey?
        /// The URL string of the portal to connect to.
        /// Defaults to the main ArcGIS Online portal.
        var portalURLString = "https://www.arcgis.com"
        /// Stores the information related to user's portal.
        var portalInfo: PortalInfo?
        /// Stores the current user's data such as username, email, etc.
        var portalUser: PortalUser?
        /// Indicates whether the model is currently loading data.
        var isLoading = false

        init() {
            self.authenticator = Authenticator(
                oAuthUserConfigurations: [.arcgisDotCom]
            )
        }

        func setAuthenticator() {
            // Sets authenticator as ArcGIS and Network challenge handlers to
            // handle authentication challenges.
            ArcGISEnvironment.authenticationManager.handleChallenges(using: authenticator)
            // Temporarily unsets the API key for this sample to use OAuth.
            apiKey = ArcGISEnvironment.apiKey
            ArcGISEnvironment.apiKey = nil
        }

        /// Removes the authenticator and restores the original state.
        func clearAuthenticator() async {
            // This removes our custom challenge handler.
            ArcGISEnvironment.authenticationManager.handleChallenges(using: nil)
            // This restores the original API key.
            ArcGISEnvironment.apiKey = apiKey
            // This signs out to clean up any remaining session.
            await signOut()
        }

        /// Signs out from the portal by revoking OAuth tokens and clearing credential stores.
        func signOut() async {
            await ArcGISEnvironment.authenticationManager.revokeOAuthTokens()
            await ArcGISEnvironment.authenticationManager.clearCredentialStores()
            portalUser = nil
            portalInfo = nil
            isLoading = false
        }

        /// Loads portal user information from the specified URL.
        func loadPortalUser() async throws {
            isLoading = true
            // This ensures loading state is cleared even if an error occurs.
            defer { isLoading = false }

            // This determines which portal to connect to.
            let portal: Portal
            if portalURLString != "https://www.arcgis.com",
               let customURL = URL(string: portalURLString) {
                // This uses custom portal URL with authentication.
                portal = Portal(url: customURL, connection: .authenticated)
            } else {
                // This uses the default ArcGIS Online portal.
                portal = Portal.arcGISOnline(connection: .authenticated)
            }

            // This loads portal information and authenticates user.
            try await portal.load()
            try await portal.user?.thumbnail?.load()
            portalUser = portal.user
            portalInfo = portal.info
        }
    }

    /// A view that manages the portal URL input, sign-in/sign-out actions, and portal loading.
    struct PortalDetailsView: View {
        /// Binding to the portal URL string.
        @Binding var url: String
        /// Binding to the user info model containing user state and data.
        @Binding var model: ShowPortalUserInfoView.Model
        /// Closure called when the portal URL is set or changed.
        var onSetUrl: (String) -> Void
        /// Closure called when the user signs out.
        var onSignOut: () -> Void
        /// Closure called to load the portal user info.
        var onLoadPortal: () -> Void

        /// State to track whether the text field is currently focused.
        @FocusState private var isTextFieldFocused: Bool

        var body: some View {
            VStack {
                TextField(
                    "Portal URL",
                    text: $url,
                    onCommit: {
                        // When the user finishes editing, load the portal and dismiss keyboard focus.
                        onLoadPortal()
                        isTextFieldFocused = false
                    }
                )
                // Prevent automatic capitalization.
                .textInputAutocapitalization(.never)
                // Use URL keyboard layout.
                .keyboardType(.URL)
                // Show "Go" button on the keyboard.
                .submitLabel(.go)
                // Bind focus state to `isTextFieldFocused`.
                .focused($isTextFieldFocused)
                .textFieldStyle(.roundedBorder)

                // Button to sign in or sign out, depending on whether a user has been set.
                Button(model.portalUser == nil ? "Sign In" : "Sign Out") {
                    if model.portalUser == nil {
                        onLoadPortal()
                    } else {
                        onSignOut()
                    }
                    // Dismiss the keyboard focus after button press.
                    isTextFieldFocused = false
                }
                .disabled(model.isLoading)
                .buttonStyle(.borderedProminent)
                .tint(.purple)
            }
            .padding(.vertical)
        }
    }

    /// A view that displays detailed information about the portal user.
    struct InfoScreen: View {
        /// A binding to the model providing user data and loading state.
        @Binding var model: ShowPortalUserInfoView.Model

        var body: some View {
            VStack {
                if model.isLoading {
                    // Show a progress indicator while loading user data.
                    ProgressView()
                        .padding()
                } else {
                    // Display additional user information text when data is loaded.
                    Text(model.portalUser?.description ?? "No user data available.")
                        .multilineTextAlignment(.center)
                        .padding()
                }
                Divider()
                // Show the user's thumbnail image as a circular avatar.
                Image(uiImage: model.portalUser?.thumbnail?.image ?? .defaultUserImage)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 150, height: 150)
                    .clipShape(Circle())

                if let portalUser = model.portalUser {
                    List {
                        LabeledContent("Username", value: portalUser.username)
                        LabeledContent("E-mail", value: portalUser.email)
                        if let creationDate = portalUser.creationDate {
                            LabeledContent("Member Since", value: creationDate, format: .dateTime.day().month().year())
                        }
                        if let portalInfo = model.portalInfo {
                            LabeledContent("Portal Name", value: portalInfo.portalName)
                        }
                    }
                    .listStyle(.plain)
                    .frame(minHeight: 300)
                }
            }
        }
    }
}

private extension OAuthUserConfiguration {
    /// The configuration of the application registered on ArcGIS Online.
    static let arcgisDotCom = OAuthUserConfiguration(
        portalURL: .portal,
        clientID: .clientID,
        redirectURL: .redirectURL
    )
}

private extension UIImage {
    /// Default placeholder image.
    static let defaultUserImage = UIImage(systemName: "person.circle")!
}

private extension URL {
    /// The URL of the portal to authenticate.
    /// - Note: If you want to use your own portal, provide URL here.
    static let portal = URL(string: "https://www.arcgis.com")!

    /// The URL for redirecting after a successful authorization.
    /// - Note: You must have the same redirect URL used here registered with your client ID.
    /// The scheme of the redirect URL is also specified in the Info.plist file.
    static let redirectURL = URL(string: "my-ags-app://auth")!
}

private extension String {
    /// A unique identifier associated with an application registered with the portal.
    /// - Note: This identifier is for a public application created by the ArcGIS Maps SDK team.
    static let clientID = "lgAdHkYZYlwwfAhC"
}

#Preview {
    ShowPortalUserInfoView()
}

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