In a command line app, I'd like to input the username and password.
But I'd like to hide the '123456' because its a password.
In bash I can use
read -s
And what's the Swifty way?
Below is the implementation of getInput.
func getInput() -> String {
// 1
let keyboard = FileHandle.standardInput
// 2
let inputData = keyboard.availableData
// 3
let strData = String(data: inputData, encoding: String.Encoding.utf8)!
// 4
return strData.trimmingCharacters(in: CharacterSet.newlines)
}
saagarjha
(Saagar Jha)
April 16, 2018, 9:18am
2
Hello @PhilCai , and welcome to the Swift Forums!
Unfortunately, as far as I'm aware, what you're trying to do has no portable solution. On Linux, you should be able to use getpass
, and on most Unices you can use the functions found in <termios.h>
, namely tcsetattr(3)
, to turn off echoing. If third-party libraries are an option, you may want to take a look at curses, which can provide this functionality.
2 Likes
Wow, thanks a lot @saagarjha . It seems curses is what I want.
eskimo
(Quinn βThe Eskimo!β)
April 17, 2018, 6:21am
4
On Linux, you should be able to use getpass β¦
FYI, getpass
exists on macOS as well .
Share and Enjoy
β
Quinn βThe Eskimo!β
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"
1 Like
Thanks @eskimo . But it will be great if there is a func readline(silent: Bool)
Here you go:
func readline(silent: Bool) -> String? {
return silent ? String(cString: getpass("")) : readLine()
}