Reputation: 791
i'm using SQLite Library and in usage it says let db = try Connection("path/to/db.sqlite3")
i have sqlite database located in documents. but when i try to make connection it throw an error call can throw but errors cannot be thrown out of a property initializer
here's my code :
import UIKit
import SQLite
class SearchViewController: UIViewController, UITextFieldDelegate {
let db = try Connection("/Users/macbookpro/Documents/db.sqlite") //error
let categoryVC = CategoryViewController()
let UseFullVC = UseFullViewController()
let MapVC = MapViewController()
let EventVC = SearchResultOnlineVC()
@IBOutlet weak var searchTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Search"
searchTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
i also try to put connection in viewDidLoad but still doesn't work
what's wrong?
Upvotes: 0
Views: 596
Reputation: 137
import UIKit
import SQLite
let sharedInstance = DBModelManager()
class DBModelManager: NSObject {
var database: Connection!
class func getInstance() -> DBModelManager
{
if(sharedInstance.database == nil)
{
do{
let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileUrl = documentDirectory.appendingPathComponent("dbname").appendingPathExtension("sqlite3")
sharedInstance.database = try Connection(fileUrl.path)
}catch{
print("DB Error \(error)")
}
}
return sharedInstance
}
}
Call DB instance this way
try DBModelManager.getInstance().database!.prepare()
Upvotes: 0
Reputation: 121057
Since the Connection
initializer can throw an exception, you need to call it in a do/catch
block.
So you should change the declaration to:
var db : Connection?
And initialize it in ViewDidLoad
:
do{
self.db = try Connection("/Users/macbookpro/Documents/db.sqlite")
} catch {
print("Unable to create connection: \(error)")
}
Upvotes: 1