vendredi 8 janvier 2016

unexpectedly found nil while unwrapping an Optional value: Swift - FMDB - executeQuery

I am new to Swift, FMDB and development in general and I and I am getting a fatal error at runtime : unexpectedly found nil while unwrapping an Optional Value. The error happens on the executeQuery line

Initial try and relevant code:

        var rightAnswer:FMResultSet?
        var memberDatabase:FMDatabase?
    ....
override func viewDidLoad() {
let path = NSBundle.mainBundle().pathForResource("1_celebs", ofType: "sqlite3")
        memberDatabase = FMDatabase(path: path)
        if memberDatabase!.open(){
            print("database is ready")//it works if I comment out the stuff in loadquestion() 
        }
        else{
            print("error finding database")
        }
...
    func loadQuestion(){
        let querySQL = "SELECT Quote, Answer, answerNumber, Celeb1, Celeb2, Celeb3, img1, img2, img3, feedbackImg, Context FROM celebs WHERE answeredRight = 'no' ORDER BY RANDOM() LIMIT 1"

        rightAnswer = memberDatabase!.executeQuery(querySQL, withArgumentsInArray: queryParameters)
        rightAnswer!.next()

So then I tried this in func loadQuestion()

let results:FMResultSet? = memberDatabase!.executeQuery(querySQL, withArgumentsInArray: nil)
        while(results?.next() == true)
        {...}

Then I tried this:

do{
   rightAnswer = try memberDatabase!.executeQuery(querySQL, withArgumentsInArray: queryParameters)
   while rightAnswer!.next(){...}
 } catch let error as NSError {
    print("failed: \(error.localizedDescription)")
 }

Then, this:

   do{
   let rs = try memberDatabase!.executeQuery(querySQL, values: nil)
    while rs.next(){...}
} catch let error as NSError {
  print("failed: \(error.localizedDescription)")
}

and I get the same error on the executeQuery line every time! If I try to get away with getting rid of the exclamation and question marks (optionals?) then I get an error on the console saying that the database could not be opened.

Aucun commentaire:

Enregistrer un commentaire