这是我的代码:
@IBAction func signUp(sender: AnyObject) {
var user = PFUser()
user.username = self.userNameTextField.text
user.password = self.passWordTextField.text
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil && (user.username != nil && user.password != nil) {
println("Sign Up successfull")
//Go to main menu
self.performSegueWithIdentifier("go-to-main-menu", sender: nil)
} else {
let errorString = error.localizedDescription
let alert = UIAlertView()
alert.title = "Invalid Signup"
alert.message = "Sorry, a username (unique) and a password are required to create a new account."
alert.addButtonWithTitle("OK")
alert.show()
println(errorString)
}
}
}
所以我的目标是在
(a) 用户名被占用
(b)用户名或密码未填写
结果:
1. 尝试在两个字段都空白的情况下注册会导致警报
2. 尝试用密码空白注册,结果没有提示,用户已保存
3. 尝试使用用户名空白注册会导致警告
因为我在 if 语句中检查 nil
,为什么会出现结果 #2?
现在,如果我将验证更改为检查零 长度字符串:
if error == nil && (user.username != "" && user.password != "")
...它因以下错误而崩溃:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
...在这条线上:
let errorString = error.localizedDescription
我看过how to add an extra attribute to Parse a Signup function ,但那是在添加我不想要或不需要的额外内容。
我也查看了“Parse SignUp Failure Adds User Regardless”,但我已经在进行文本检查了。
最佳答案
您应该通过使用 countElements
检查字符串的长度来检查长度 os 是否大于 0。此外,我会删除 user.username
和user.password
检查:
if error == nil && countElements(user.username) > 0 && countElements(user.password) > 0 {
关于iOS- swift : Parse signup - new user is saved even though text validation should prevent it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28661299/