ina patodiya ina patodiya - 5 months ago 7
Swift Question

how can i show retrieved data from database in not a present view controller but another one in ios with using swift

i'm making database in main view controller and now i want to retrieve its stored data in to next view controller but i don't know, can any one give me answer of it.

a code block:

override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let filemgr = NSFileManager.defaultManager()
let dirPaths =
NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
.UserDomainMask, true)

let docsDir = dirPaths[0]
let path = (docsDir as NSString).stringByAppendingPathComponent("contacts.db")


databasePath = path

if !filemgr.fileExistsAtPath(databasePath as String) {

let contactDB = FMDatabase(path: databasePath as String)

if contactDB == nil {
print("Error: \(contactDB.lastErrorMessage())")
}

if contactDB.open() {
let sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)"
if !contactDB.executeStatements(sql_stmt) {
print("Error: \(contactDB.lastErrorMessage())")
}
contactDB.close()
} else {
print("Error: \(contactDB.lastErrorMessage())")
}
}

}


using this code i made database
but how can i retrieve its data in next view controller again i'm repeating not on a same page another page i want to display this.

Answer

Do not implement your database in a view controller but in your app delegate.

Example:

// declare global database
var db:FMDatabase?

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    // do your database init stuff here
}