How to Get the User "Name" Using Swift

Displaying the username of current user (Swift)

Swift 4.2

let userName = NSUserName()
let fullUserName = NSFullUserName()

Access user's first name and other information in firebase using Swift

There are a few ways you can do this but just one thing I want to point out is that when you check if the user has logged in with if let userId = Auth.auth().currentUser?.uid you then proceed to retrieve every user document with let userName = db.collection("users").getDocuments() which is probably making it much more slower than it needs to be. And this will get slower the more popular your app becomes because downloading more users takes more time. This is an easy fix by just adding one small thing:

let userName = db.collection("users").document(userId).getDocument()
This only gets 1 document instead of all.

Also right after that you loop through each document you've retrieved and perform

if let firstUserDoc = snapshot?.documents.first {
let welcomeName = firstUserDoc["first_name"] as! String
self.errorLabel.text = "Hey, \(welcomeName) welcome!"
}

This block is run snapshot!.documents.count (Number of users you have in your app) amount of times which again seems unnecessary as it does the same thing each iteration. Remove the loop and doing it 1 time will be so much faster.

This is how your code should look after:

if let userId = Auth.auth().currentUser?.uid {
db.collection("users").document(userId).getDocument { docSnapshot, error in
if let error = error {
errorLabel.textColor = UIColor.red
errorLabel.text = "Error getting documents: \(error)"
} else {
let welcomeName = docSnapshot!.get("first_name") as! String
errorLabel.text = "Hey, \(welcomeName) welcome!"
}
}
} //end if
// ...Other code

This should work but if you want an even faster way to do this and don't use the Auth.auth().currentUser!.displayName property then you can store their first name in that and simply reduce your code to:

if let userFirstName = Auth.auth().currentUser?.displayName! {
errorLabel.text = "Hey, \(userFirstName) welcome!"
} else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(identifier: "login")
vc.modalPresentationStyle = .overFullScreen
present(vc, animated: true)
}

^ This would be ideal if your app refers to all users by their first names instead of their usernames (plus it'll show up in verification emails as well)

One last thing I'd like to mention is in your original post I don't understand how you were guaranteeing the first document of the snapshot to be the user you want. If it's an old user using the app then someone else's name would probably come up as newer users will be at the top of the list. As this is your first app I want to stress the importance of writing tests for your functions. Be sure to read up on Unit Tests and UI Tests (mainly Unit Tests for your purposes), they really make a big difference. It's not too hard to learn either. I remember when I first started I avoided them like the plague because I thought they took too much time. But in the long run they save you thousands of hours by making your code as bug free as possible and even help structuring your code better by making it more modular!

Hope this helps and best of luck with your first app!

How to get username from AWS Cognito - Swift

Prerequisites:

  • App registered with MobileHub
  • Cognito Setup in MobileHub
  • Mobilehub integrated with Swift Project using AWS SDK

If you're like me, you did this with little to no difficulty and now you're stuck trying to get the username and other parameters from the logged in user. There are a lot of answers, but thus far, I haven't stumbled upon one that gets you all the way there.

I was able to piece this together from various sources:

   func getUsername() {
//to check if user is logged in with Cognito... not sure if this is necessary
let identityManager = AWSIdentityManager.default()
let identityProvider = identityManager.credentialsProvider.identityProvider.identityProviderName

if identityProvider == "cognito-identity.amazonaws.com" {
print("************LOGGED IN WITH COGNITO************")
let serviceConfiguration = AWSServiceConfiguration(region: .USWest2, credentialsProvider: nil)
let userPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "YourClientID", clientSecret: "YourSecretKey", poolId: "YourPoolID")
AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: userPoolConfiguration, forKey: "YourPoolName (typically formatted as YourAppName_userpoool_MOBILEHUB_12345678")
let pool = AWSCognitoIdentityUserPool(forKey: "YourPoolName")
// the following line doesn't seem to be necessary and isn't used so I've commented it out, but it is included in official documentation
// let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USWest2, identityPoolId: "YourPoolID", identityProviderManager:pool)
if let username = pool.currentUser()?.username {
print("Username Retrieved Successfully: \(username)")
} else {
print("Error getting username from current user - attempt to get user")
let user = pool.getUser()
let username = user.username
print("Username: \(username)")
}
}
}

To get your ClientID, Secret Key, and PoolID, check your awsconfiguration.json

To get your PoolName, login to MobileHub, and in your project's backend, go to User Sign in, click Email and Password, then click Edit in Cognito. The following page will have your Pool Name as "YourAppName_userpool_MOBILEHUB_12345678"

Edit: To get all of the attributes as well:

  if let userFromPool = pool.currentUser() {        
userFromPool.getDetails().continueOnSuccessWith(block: { (task) -> Any? in
DispatchQueue.main.async {

if let error = task.error as NSError? {
print("Error getting user attributes from Cognito: \(error)")
} else {
let response = task.result
if let userAttributes = response?.userAttributes {
print("user attributes found: \(userAttributes)")
for attribute in userAttributes {
if attribute.name == "email" {
if let email = attribute.value {
print("User Email: \(email)")
}
}
}


Related Topics



Leave a reply



Submit