jeudi 29 janvier 2015

Swift: Set UITextField.text from class (retrieved value from SQLite)

I am using Swift with SQLite.swift. I have the following UIViewController:



class LoginViewController: UIViewController {

@IBOutlet weak var emailField: UITextField!

func setEmailAddress(email:String){
emailField.text = email
}

override func viewDidLoad() {
MySQLite().updateLatestEmailAddressFromUserTable() // breaks here (email is in console, though...)
}

}


Then I am trying to update it's value (through the setEmailAddress function) from another class:



class MySQLite {

func updateLatestEmailAddressFromUserTable(){

let dbPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String
let db = Database("\(dbPath)/db.sqlite3")

let users = db["users"]
let id = Expression<Int>("id")
let email = Expression<String>("email")
let time = Expression<Int>("time")

for user in users.limit(1).order(time.desc) {

println(user[email]) // this works, correctly outputs in console: email@domain.com
LoginViewController().setEmailAddress(user[email]) // breaks here

}
}

}


above code gives me the following error



fatal error: unexpectedly found nil while unwrapping an Optional value


To explain a little further: I am retrieving the most recent entry in SQLite table to get the user's email address and update the text field in the login view controller. This allows for easier log in for returning users.


I have been struggling with this for over 2 hours now and trying various things. The main problem I believe is that when I try to simply return the email address as string from my second function and set the field directly from LoginViewController, it doesn't work (SQLite related code was not "executed" yet I believe).


possibly related thread (Obj-C): set UITextField.text from another class


Aucun commentaire:

Enregistrer un commentaire