5

I am trying to use Parse written with Swift. I am able to log in without any trouble but I am struggling with telling my app that the user is logged in.

I am using logInWithUsernameInBackground and I simply want to return a boolean if the log in succeeded.

When I use:

func authenticateUser() -> Bool{
    PFUser.logInWithUsernameInBackground(userName.text, password: passwordField.text, block: {
        (user,error) in
        return error === nil
    })
}

I get the error "Bool is not convertible to Void" which makes sense.

So if I change line 3 to read:

(user,error) -> Bool in

I end up with the error "Missing argument for parameter selector in call"

However, This method doesn't require a selector parameter.

So where am I going wrong? How do I return a bool based on whether or not there was an error at log in?

4

1 回答 1

9

根据您编写的代码,如果您想返回 Bool,您可以这样做:

func authenticateUser() -> Bool{
    PFUser.logInWithUsernameInBackground(userName.text, password: passwordField.text, block: {
        (user,error) in
        return error === nil
    })

    return true // This is where the bool is returned
}

但是,根据您的代码,您想要做的是:

func authenticateUser(completion:(Bool) -> ()) {
    PFUser.logInWithUsernameInBackground(userName.text, password: passwordField.text, block: {
        (user,error) in
        completion(error === nil)
    })
}

您可以通过以下方式之一调用调用:

authenticateUser(){
    result in
    if result {
        println("Authenticated")
    } else {
        println("Not authenticated")
    }
}

或者

authenticateUser({
  result in
    if result {
        println("Authenticated")
    } else {
        println("Not authenticated")
    }
})

第一个是速记,当你在闭包之前有其他参数时更方便。

这意味着您正在取回您的 Bool 以了解您是否进行了异步身份验证。

顺便说一句,你真的只需要做error == nil

于 2014-12-03T07:11:29.910 回答