When user signs up for an account with our mobile app, we invite them to come up with a secure password. It is user friendly, if our app can suggest them a secure password by generating one and placing next to a password text field, so that they can pick it and use.
The code below will help you generate an alphanumeric string of random characters which you can use to auto generate a secure password for your users. Also, the code below allows you to generate a password of desired length. Although the longer the password the more difficult it is to brute force it, a very long password would be difficult for user to remember. In my opinion 8-10 characters password is a good balance.
Generate User Password Code Example in Swift
func generatePassword(passwordLength: Int) -> String { let passwordMaterial : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let passwordMaterialLength = UInt32(passwordMaterial.length) var returnValue = "" for _ in 0 ..< passwordLength { let randomPosition = arc4random_uniform(passwordMaterialLength) var character = passwordMaterial.character(at: Int(randomPosition)) returnValue += NSString(characters: &character, length: 1) as String } return returnValue } let myPassword = generatePassword(passwordLength: 10) print("Secure password: \(myPassword)")
I hope this short code example is helpful to you!
Building Mobile Apps for iOS with Swift – Video Courses