Unconquered82
Unconquered82

Reputation: 551

Fatal Error in Swift unwrapping an Optional value using data from Parse

I am trying to display a currently logged in username and I am getting a fatal error about an unexpected nil for an optional value. I've searched several of the other questions related to my issue (using "if let") and attempted the solution but for some reason I cannot get this code to display in my label even though I am ,in fact, showing a value for my variable on debug. My code is as follows:

import UIKit
import Parse

class DashboardViewController: UIViewController {

@IBOutlet var welcomeText: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()


}

override func viewWillAppear(animated: Bool) {

    if  let currentUser = PFUser.currentUser()?.username {

        welcomeText.text = "Welcome  \(currentUser)!"

    } else {

        welcomeText.text = "Welcome"
    }


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

  }
}

I have even tried (as I posted this) moving my code to the viewWillAppear() function to see if that made a difference considering that has helped in the past, but no luck. Any help would be greatly appreciated!

error: as you can see here, I have a value on debug, and the error in the lower right.

Upvotes: 0

Views: 109

Answers (2)

Ben Kane
Ben Kane

Reputation: 10040

It's your label that is nil. It looks to me like the connection for the label between Interface Builder and your code got disconnected. You'll need to right click and drag from the label to the outlet property to form the connection again.

Upvotes: 3

Armin Scheithauer
Armin Scheithauer

Reputation: 600

Try below code, put the parse code separate. I guess you try to assign the Parse data before it is ready.

import UIKit
import Parse

class DashboardViewController: UIViewController {

@IBOutlet var welcomeText: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()
welcomeMessage()

}

override func viewWillAppear(animated: Bool) {

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

  }

    func welcomeMessage () {
    if  let currentUser = PFUser.currentUser()?.username {

            welcomeText.text = "Welcome  \(currentUser)!"

        } else {

            welcomeText.text = "Welcome"
        }
    }

}

It still would be very helpful to see more code, where is your code to fetch the user? Did you try to set the label Text there as well? Did that work?

Upvotes: 0

Related Questions