Reputation: 551
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:
Upvotes: 0
Views: 109
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
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