解析PFUser.currentUser返回nil-Swift [英] Parse PFUser.currentUser returns nil - Swift

查看:99
本文介绍了解析PFUser.currentUser返回nil-Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Parse登录用户.在我的应用打开时,LaunchVieWController会确定用户是否已经登录:

I am logging in my users using Parse. As my app opens my LaunchVieWController determines whether users are already signed in or not:

override func viewDidLoad() {
    super.viewDidLoad()

    //Make sure cached users don't have to log in every time they open the app
    var currentUser = PFUser.currentUser()
    println(currentUser)
    if currentUser != nil {
        dispatch_async(dispatch_get_main_queue()) {
            self.performSegueWithIdentifier("alreadySignedIn", sender: self)
        }
    } else {
        dispatch_async(dispatch_get_main_queue()) {
            self.performSegueWithIdentifier("showSignUpIn", sender: self)
        }
    }
}

如果用户已经登录,则将他们带到下面描述的表格视图中.如果未登录,则会被带到一个视图,在该视图中可以进入注册视图或登录视图.

If users are already signed in they are taken to the table view described below. If they are not logged in, they are taken to a view in which they can go to the signup view or the login view.

我的注册工作正常,并注册了用户,然后将其重定向到表视图. 这是注册功能(与登录功能位于单独的控制器中):

My signup works perfectly fine, and signs up users and then redirects them to the table view. Here is the signup function (it is in a separate controller from the login function):

func processSignUp() {

    var userEmailAddress = emailAddress.text
    var userPassword = password.text

    // Ensure username is lowercase
    userEmailAddress = userEmailAddress.lowercaseString

    // Add email address validation

    // Start activity indicator
    activityIndicator.hidden = false
    activityIndicator.startAnimating()

    // Create the user
    var user = PFUser()
    user.username = userEmailAddress
    user.password = userPassword
    user.email = userEmailAddress

    user.signUpInBackgroundWithBlock {
        (succeeded: Bool, error: NSError?) -> Void in
        if error == nil {

            dispatch_async(dispatch_get_main_queue()) {
                self.performSegueWithIdentifier("signInToNavigation", sender: self)
            }

        } else {

            self.activityIndicator.stopAnimating()

            if let message: AnyObject = error!.userInfo!["error"] {
                self.message.text = "\(message)"
            }               
        }
    }
}

我的登录功能如下:

@IBAction func signIn(sender: AnyObject) {
    var userEmailAddress = emailAddress.text
    userEmailAddress = userEmailAddress.lowercaseString
    var userPassword = password.text

   PFUser.logInWithUsernameInBackground(userEmailAddress, password:userPassword) {
        (user: PFUser?, error: NSError?) -> Void in
        if user != nil {
            dispatch_async(dispatch_get_main_queue()) {
                self.performSegueWithIdentifier("signInToNavigation", sender: self)
            }
        } else {
            if let message: AnyObject = error!.userInfo!["error"] {
                self.message.text = "\(message)"
            }
        }
    }
}

用户登录后,他们将被发送到表视图.在该表视图中,我想通过以下函数访问当前用户对象,因为我想根据用户是谁来加载不同的数据:

After users log in they are sent to a table view. In that table view I am trying to access the current user object in the following function, as I want to load different data based on who the user is:

override func queryForTable() -> PFQuery {
    var query = PFQuery(className:"MyClass")
    query.whereKey("userID", equalTo: PFUser.currentUser()!)
    return query
}

当我尝试与用户登录时,抛出以下错误:致命错误:在解开Optional值时意外发现nil".似乎PFUser.currentUser()对象为nil.

When I try to log in with a user I get thrown the following error: "fatal error: unexpectedly found nil while unwrapping an Optional value". It seems like the PFUser.currentUser() object is nil.

注册后将用户发送到表格视图时,PFUser.currentUser()对象即已设置并正常工作.

When users are sent to the table view after signing up the PFUser.currentUser() object is set and works perfectly.

我的猜测是这是因为PFUser.logInWithUsernameInBackground在后台发生,并且我的查询正试图在PFUser.currentUser()对象加载之前获取它.无论如何,我可以解决此问题吗?在表视图中,需要PFUser.currentUser()的值才能加载表数据.我能以某种方式确保在调用函数之前(例如,通过不在后台线程中加载用户)为当前用户对象分配PFUser.currentUser()吗?

My guess is that this is because of the fact that the PFUser.logInWithUsernameInBackground is happening in the background and that my query is trying to get the PFUser.currentUser() object before it has been loaded. Is there anyway I can work around this issue? In the table view the value of PFUser.currentUser() is needed to load the table data. Can I somehow make sure that PFUser.currentUser() gets assigned with the current user object before the function gets called (for example, by not loading in users in the background thread)?

非常感谢所有帮助!

我已经用一些其他代码更新了此帖子,以帮助突出显示我可能会丢失的任何错误.

推荐答案

我发现出现此问题的原因是segue signInToNavigation是通过登录"按钮而不是从登录视图控制器本身连接的.这导致segue在执行登录功能之前执行,因此在加载表视图时尚未分配PFUser.currentUser()对象.我通过重新布线来解决此问题.我这边愚蠢的滑倒.

I discovered that this problem appeared because the segue signInToNavigation was wired from the Login-button, instead from the login view controller itself. This resulted in the segue being executed before the login function was executed, and therefore the PFUser.currentUser()object was not yet assigned when the table view loaded. I solved this by rewiring the segues. Stupid slip-up on my side.

感谢赖安·克莱格(Ryan Kreager)和温恩(Wain)花时间帮助我弄清楚这个问题!

Thanks to Ryan Kreager and Wain for taking time to help me figure out this issue!

这篇关于解析PFUser.currentUser返回nil-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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