ios - Swift/MongoDB 服务器 - 无法读取数据,因为它的格式不正确。

标签 ios swift xcode mongodb

我正在开发一个带有登录屏幕的简单应用程序。在我的 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 上的usernamepassword 变量是否隐式解包可选?即使如此,我们通常也不会在 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/

相关文章:

ios - Xcode 中的单个 .swift 文件是否可以包含 iOS 应用程序的完整源代码?

ios - 旧的 RPG 滚动文本,但用(点点点)分解文本 block

ios - Realm 无法在后台线程中解密数据库错误

ios - 将以下代码转换为 Swift 2.2

ios - 如何存储字典数组并将其显示在 swift 4 的 Collection View 中

ios - 点击imageview的动画,酷炫的小放大

iphone - 如何从Cocos2D返回UIkit?

ios - 使用 PanGestureRecognizer 创建 UIView 并在不抬起手指的情况下激活它

swift - Firebase 身份验证 : Password must contain capital letter

swift - 当 Sprite 接触到另一个 Sprite 时重置