我正在开发一个带有登录屏幕的简单应用程序。在我的 View Controller (LoginViewController) 的代码中,我创建了以下函数,该函数应该允许用户注册。但是,当我测试该应用程序时,控制台告诉我“无法读取数据,因为它的格式不正确。”
@IBAction func onSignUp(_ sender: Any) {
let newUser = PFUser()
newUser.username = usernameField.text as String!
newUser.password = passwordField.text as String!
newUser.signUpInBackground { (success: Bool, error: Error?) in
if success {
print("Created User")
} else {
print(error!.localizedDescription)
}
}
}
我怀疑我遇到了某种类型错误?文本字段是否需要字符串以外的数据类型?知道为什么会发生这种情况吗?有已知的解决方案吗?
最佳答案
这两行有点奇怪:
newUser.username = usernameField.text as String!
newUser.password = passwordField.text as String!
PFUser 上的username
和password
变量是否隐式解包可选?即使如此,我们通常也不会在 Swift 中编写这样的代码。我们可能会写一些类似的内容:
@IBAction func onSignUp(_ sender: Any) {
guard let usernameText = usernameField.text, let passwordText = passwordField.text else {return}
let newUser = PFUser()
newUser.username = usernameText
newUser.password = passwordText
newUser.signUpInBackground { (success: Bool, error: Error?) in
if success {
print("Created User")
} else {
print(error!.localizedDescription)
}
}
}
试试这个
关于ios - Swift/MongoDB 服务器 - 无法读取数据,因为它的格式不正确。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52428998/