Manage user attributes
Fetch the current user's attributes
Invoke the following api to get the list of attributes assigned to the user.
1func fetchAttributes() async {2 do {3 let attributes = try await Amplify.Auth.fetchUserAttributes()4 print("User attributes - \(attributes)")5 } catch let error as AuthError{6 print("Fetching user attributes failed with error \(error)")7 } catch {8 print("Unexpected error: \(error)")9 }10}
Update user attribute
Invoke the update api for creating new or updating existing user attributes.
1func updateAttribute() async {2 do {3 let updateResult = try await Amplify.Auth.update(4 userAttribute: AuthUserAttribute(.phoneNumber, value: "+2223334444")5 )6
7 switch updateResult.nextStep {8 case .confirmAttributeWithCode(let deliveryDetails, let info):9 print("Confirm the attribute with details send to - \(deliveryDetails) \(String(describing: info))")10 case .done:11 print("Update completed")12 }13 } catch let error as AuthError {14 print("Update attribute failed with error \(error)")15 } catch {16 print("Unexpected error: \(error)")17 }18}
Verify user attribute
Some attributes require confirmation for the attribute update to complete. If the attribute need to be confirmed, the result of the above api will be CONFIRM_ATTRIBUTE_WITH_CODE
. A confirmation code will be sent to the delivery medium mentioned in the delivery details. When the user gets the confirmation code, you can present a UI to the user to enter the code and invoke the confirm attribute api with their input:
1func confirmAttribute() async {2 do {3 try await Amplify.Auth.confirm(userAttribute: .email, confirmationCode: "390739")4 print("Attribute verified")5 } catch let error as AuthError {6 print("Update attribute failed with error \(error)")7 } catch {8 print("Unexpected error: \(error)")9 }10}
Resend verification code
If the code has expired or the user needs to resend the confirmation code, invoke the resend api as shown below:
1func resendCode() async {2 do {3 let deliveryDetails = try await Amplify.Auth.resendConfirmationCode(forUserAttributeKey: .email)4 print("Resend code send to - \(deliveryDetails)")5 } catch let error as AuthError {6 print("Resend code failed with error \(error)")7 } catch {8 print("Unexpected error: \(error)")9 }10}