Swift-解析-检查是否使用了用户名 [英] Swift - Parse - Check if username is taken

查看:84
本文介绍了Swift-解析-检查是否使用了用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个将用户名作为参数的函数,并检查是否使用了该用户名(通过将其与Parse数据库中的其他PFUser进行比较.此函数在我的视图控制器类中.(我知道对此也有类似的问题,但是它们不能提供高质量的答案,并且比这更笼统,或者在Swift中都不是.

I am trying to create a function that takes a username as a parameter and checks to see if that username is taken (by comparing it to other PFUsers in the Parse database. This function is in my view controller class. (I know there are similar questions to this but they do not provide quality answers and are more general than this or are not in Swift).

func usernameIsTaken(username: String) -> Bool {

    //bool to see if username is taken
    var isTaken: Bool = false

    //access PFUsers
    var query : PFQuery = PFUser.query()!
    query.whereKey("User",  equalTo: username)

    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) in

        if error == nil {
            if (objects!.count > 0){
                isTaken = true
                println("username is taken")
            } else {
                println("Username is available. ")
            }
        } else {
            println("error")
        }
    }

    return isTaken

}

问题是if语句中的条件始终为false,因此即使使用了用户名也始终在控制台中打印"Username is available".即使使用了用户名也从不打印"Username istake".我应该在嵌套的if语句中输入什么来检查用户名是否与另一个PFUser匹配?

The problem is that the condition in the if statement is always false so "Username is available" always prints in the console even if the username is taken."Username is taken" is never printed even when the username is taken. What should I put in the nested if statement to check if the username matches another PFUser?

推荐答案

您正在查询User(类)密钥,但是需要查询特定的密钥,例如email.

You are querying for User (class) key, but you need to query for a specific key, for example email.

// First get user's inputted email
let enteredEmailAddress = "sample@gmail.com"

// Then query and compare
var query = PFQuery(className: "_User")
query.whereKey("email", equalTo: enteredEmailAddress)
query.findObjectsInBackgroundWithBlock {
    (objects: [AnyObject]?, error: NSError?) in
    if error == nil {
        if (objects!.count > 0){
            isTaken = true
            println("username is taken")
        } else {
            println("Username is available. ")
        }
    } else {
        println("error")
    }
}

这篇关于Swift-解析-检查是否使用了用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆